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,96 @@
<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.41021</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{27488D51-440E-4549-AC2D-304F5F622173}</ProjectGuid>
<OutputType>Library</OutputType>
<StartupObject>
</StartupObject>
<RootNamespace>AccessHTMLDOMControl</RootNamespace>
<AssemblyName>AccessHTMLDOMControl</AssemblyName>
<MyType>Windows</MyType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\</OutputPath>
<DocumentationFile>AccessHTMLDOMControl.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DocumentationFile>AccessHTMLDOMControl.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Data" />
<Import Include="System.Drawing" />
<Import Include="System.Diagnostics" />
<Import Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\MyApplication.vb">
<AutoGen>True</AutoGen>
<DependentUpon>MyApplication.myapp</DependentUpon>
</Compile>
<Compile Include="UserControl1.vb">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UserControl1.Designer.vb">
<DependentUpon>UserControl1.vb</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\MyResources.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>MyResources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\MySettings.vb">
<AutoGen>True</AutoGen>
<DependentUpon>MySettings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\MyResources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>MyResources.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="UserControl1.resx">
<DependentUpon>UserControl1.vb</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\MyApplication.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>MyApplication.vb</LastGenOutput>
</None>
<None Include="My Project\MySettings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>MySettings.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{94E38DFF-614B-4cbd-B67C-F211BB35CE8B}" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
</Project>
@@ -0,0 +1,33 @@
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("AccessHTMLDOMControl")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("MS")>
<Assembly: AssemblyProduct("AccessHTMLDOMControl")>
<Assembly: AssemblyCopyright("Copyright @ MS 2004")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("523c74b8-00fd-42f2-b9ee-378bf6672a91")>
' 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 Build and Revision Numbers
' by using the '*' as shown below:
<Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="Windows-1252"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>1</ApplicationType>
</MyApplicationData>
@@ -0,0 +1,12 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
@@ -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,61 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Imports System.IO
Imports System.Resources
Namespace My.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.
<Microsoft.VisualBasic.HideModuleName()> _
Module MyResources
Private _resMgr As System.Resources.ResourceManager
Private _resCulture As System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> _
Public ReadOnly Property ResourceManager() As System.Resources.ResourceManager
Get
If (_resMgr Is Nothing) Then
Dim temp As System.Resources.ResourceManager = New System.Resources.ResourceManager("$safeprojectname$.MyResources", GetType(MyResources).Assembly)
System.Threading.Thread.MemoryBarrier
_resMgr = temp
End If
Return _resMgr
End Get
End Property
'<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 Property Culture() As System.Globalization.CultureInfo
Get
Return _resCulture
End Get
Set
_resCulture = value
End Set
End Property
End Module
End Namespace
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='iso-8859-1'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)" GeneratedClassNamespace="" GeneratedClassName="MySettings">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,38 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Partial Friend NotInheritable Class MySettings
Inherits System.Configuration.ApplicationSettingsBase
Private Shared m_Value As MySettings
Private Shared m_SyncObject As Object = New Object
<System.Diagnostics.DebuggerNonUserCode()> _
Public Shared ReadOnly Property Value() As MySettings
Get
If (MySettings.m_Value Is Nothing) Then
System.Threading.Monitor.Enter(MySettings.m_SyncObject)
If (MySettings.m_Value Is Nothing) Then
Try
MySettings.m_Value = New MySettings
Finally
System.Threading.Monitor.Exit(MySettings.m_SyncObject)
End Try
End If
End If
Return MySettings.m_Value
End Get
End Property
End Class
@@ -0,0 +1,40 @@
Partial Public Class UserControl1
Inherits System.Windows.Forms.UserControl
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'UserControl1 overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.SuspendLayout()
'
'UserControl1
'
Me.Name = "UserControl1"
Me.Size = New System.Drawing.Size(463, 481)
Me.ResumeLayout(False)
End Sub
End Class
@@ -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,10 @@
Public Class UserControl1
'<SNIPPET1>
Private Sub UserControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If (Me.Site IsNot Nothing) Then
Dim Doc As HtmlDocument = CType(Me.Site.GetService(Type.GetType("System.Windows.Forms.HtmlDocument")), HtmlDocument)
End If
End Sub
'</SNIPPET1>
End Class
@@ -0,0 +1,224 @@
'<Snippet1>
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Text
Imports System.IO
' A simple form that represents a window in our application
Public Class AppForm1
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
Me.Size = New System.Drawing.Size(300, 300)
Me.Text = "AppForm1"
End Sub
End Class
' A simple form that represents a window in our application
Public Class AppForm2
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
Me.Size = New System.Drawing.Size(300, 300)
Me.Text = "AppForm2"
End Sub
End Class
'<Snippet2>
' The class that handles the creation of the application windows
Public Class MyApplicationContext
Inherits ApplicationContext
Private _formCount As Integer
Private _form1 As AppForm1
Private _form2 As AppForm2
Private _form1Position As Rectangle
Private _form2Position As Rectangle
Private _userData As FileStream
'<Snippet5>
Public Sub New()
MyBase.New()
_formCount = 0
' Handle the ApplicationExit event to know when the application is exiting.
AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
Try
' Create a file that the application will store user specific data in.
_userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate)
Catch e As IOException
' 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()
End Try
' Create both application forms and handle the Closed event
' to know when both forms are closed.
_form1 = New AppForm1()
AddHandler _form1.Closed, AddressOf OnFormClosed
AddHandler _form1.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
_form2 = New AppForm2()
AddHandler _form2.Closed, AddressOf OnFormClosed
AddHandler _form2.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
' Get the form positions based upon the user specific data.
If (ReadFormDataFromFile()) Then
' 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
End If
' Show both forms.
_form1.Show()
_form2.Show()
End Sub
Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
' 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
End Try
End Sub
'</Snippet5>
Private Sub OnFormClosing(ByVal sender As Object, ByVal e As CancelEventArgs)
' When a form is closing, remember the form position so it
' can be saved in the user data file.
If TypeOf sender Is AppForm1 Then
_form1Position = CType(sender, Form).Bounds
ElseIf TypeOf sender Is AppForm2 Then
_form2Position = CType(sender, Form).Bounds
End If
End Sub
'<Snippet3>
Private Sub OnFormClosed(ByVal sender As Object, ByVal e As EventArgs)
' When a form is closed, decrement the count of open forms.
' When the count gets to 0, exit the app by calling
' ExitThread().
_formCount = _formCount - 1
If (_formCount = 0) Then
ExitThread()
End If
End Sub
'</Snippet3>
Private Function WriteFormDataToFile() As Boolean
' Write the form positions to the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = rectConv.ConvertToString(_form1Position)
Dim form2pos As String = rectConv.ConvertToString(_form2Position)
Dim dataToWrite As Byte() = 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
End Try
End Function
Private Function ReadFormDataFromFile() As Boolean
' Read the form positions from the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim data As String
If (_userData.Length <> 0) Then
Dim dataToRead(_userData.Length - 1) As Byte
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 e As IOException
Dim errorInfo As String = e.ToString()
' An error occurred while attempt to read, return false.
Return False
End Try
' Parse out the data to get the window rectangles
data = encoding.GetString(dataToRead)
Try
' Convert the string data to rectangles
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = data.Substring(1, data.IndexOf("~", 1) - 1)
_form1Position = CType(rectConv.ConvertFromString(form1pos), Rectangle)
Dim form2pos As String = data.Substring(data.IndexOf("~", 1) + 1)
_form2Position = CType(rectConv.ConvertFromString(form2pos), Rectangle)
Return True
Catch
' Error occurred while attempting to convert the rectangle data.
' Return false to use default values.
Return False
End Try
Else
' No data in the file, return false to use default values.
Return False
End If
End Function
End Class
'<Snippet4>
Public Module MyApplication
Public Sub Main()
' Create the MyApplicationContext, that derives from ApplicationContext,
' that manages when the application should exit.
Dim context As MyApplicationContext = New MyApplicationContext()
' Run the application with the specific context. It will exit when
' all forms are closed.
Application.Run(context)
End Sub
End Module
'</Snippet4>
'</Snippet2>
'</Snippet1>
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<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>{2052A2CE-1D66-40A2-9C64-DD04B931EB2B}</ProjectGuid>
<OutputType>WinExe</OutputType>
<StartupObject>ApplicationSettings.Architecture.My.MyApplication</StartupObject>
<RootNamespace>ApplicationSettings.Architecture</RootNamespace>
<AssemblyName>ApplicationSettings.Architecture</AssemblyName>
<MyType>WindowsForms</MyType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ApplicationSettings.Architecture.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ApplicationSettings.Architecture.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</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>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Drawing" />
<Import Include="System.Diagnostics" />
<Import Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="DummyProviderClass.vb" />
<Compile Include="Form1.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.vb">
<DependentUpon>Form1.vb</DependentUpon>
<SubType>Form</SubType>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.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,29 @@
'<SNIPPET1>
Imports System.Configuration
<SettingsProvider("SqlSettingsProvider")> _
Public Class CustomSettings
Inherits ApplicationSettingsBase
' Implementation goes here.
End Class
'</SNIPPET1>
Public MustInherit Class DummyProviderBase
Public MustOverride Property ApplicationName() As String
End Class
Public Class DummyProviderClass
Inherits DummyProviderBase
'<SNIPPET2>
Public Overrides Property ApplicationName() As String
Get
ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
End Get
Set(ByVal value As String)
' Do nothing.
End Set
End Property
'</SNIPPET2>
End Class
@@ -0,0 +1,27 @@
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
components = New System.ComponentModel.Container()
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Text = "Form1"
End Sub
End Class
@@ -0,0 +1,38 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.ApplicationSettings.Architecture.Form1
End Sub
End Class
End Namespace
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Form1</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>0</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
@@ -0,0 +1,34 @@
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("ApplicationSettings.Architecture")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("ApplicationSettings.Architecture")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2005")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("95c212cb-0c18-4f03-881a-a34f02b79e58")>
' 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 Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
@@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'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.
'<summary>
' A strongly-typed resource class, for looking up localized strings, etc.
'</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ApplicationSettings.Architecture.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'<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)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
@@ -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,73 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.ApplicationSettings.Architecture.My.MySettings
Get
Return Global.ApplicationSettings.Architecture.My.MySettings.Default
End Get
End Property
End Module
End Namespace
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<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>{BA320BE8-C1E9-46CE-B5E9-2CFB08216B95}</ProjectGuid>
<OutputType>WinExe</OutputType>
<StartupObject>AppSettingsArchitectureProjectVB.My.MyApplication</StartupObject>
<RootNamespace>AppSettingsArchitectureProjectVB</RootNamespace>
<AssemblyName>AppSettingsArchitectureProjectVB</AssemblyName>
<MyType>WindowsForms</MyType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>AppSettingsArchitectureProjectVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>AppSettingsArchitectureProjectVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</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>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Drawing" />
<Import Include="System.Diagnostics" />
<Import Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.vb">
<DependentUpon>Form1.vb</DependentUpon>
<SubType>Form</SubType>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="MyAppSettings.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Form1.resx">
<SubType>Designer</SubType>
<DependentUpon>Form1.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.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,35 @@
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.SuspendLayout()
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
End Class
@@ -0,0 +1,120 @@
<?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>
</root>
@@ -0,0 +1,17 @@
Public Class Form1
'<SNIPPET3>
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Mus.Save()
End Sub
'</SNIPPET3>
'<SNIPPET2>
Dim Mus As MyUserSettings
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Mus = New MyUserSettings()
Mus.BackgroundColor = Color.AliceBlue
Me.DataBindings.Add(New Binding("BackColor", Mus, "BackgroundColor"))
End Sub
'</SNIPPET2>
End Class
@@ -0,0 +1,38 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AppSettingsArchitectureProjectVB.Form1
End Sub
End Class
End Namespace
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Form1</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>0</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
@@ -0,0 +1,34 @@
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("AppSettingsArchitectureProjectVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("AppSettingsArchitectureProjectVB")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2005")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("cb5e066f-6bf9-4152-8dcd-91fa13d0e637")>
' 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 Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
@@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'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.
'<summary>
' A strongly-typed resource class, for looking up localized strings, etc.
'</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("AppSettingsArchitectureProjectVB.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'<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)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
@@ -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,73 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.AppSettingsArchitectureProjectVB.My.MySettings
Get
Return Global.AppSettingsArchitectureProjectVB.My.MySettings.Default
End Get
End Property
End Module
End Namespace
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,18 @@
'<SNIPPET1>
Imports System.Configuration
Public Class MyUserSettings
Inherits ApplicationSettingsBase
<UserScopedSetting()> _
<DefaultSettingValue("white")> _
Public Property BackgroundColor() As Color
Get
BackgroundColor = Me("BackgroundColor")
End Get
Set(ByVal value As Color)
Me("BackgroundColor") = value
End Set
End Property
End Class
'</SNIPPET1>
@@ -0,0 +1,52 @@
Public Partial Class CodeForm
Inherits System.Windows.Forms.Form
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.RichTextBox1 = New System.Windows.Forms.RichTextBox
Me.SuspendLayout()
'
'RichTextBox1
'
Me.RichTextBox1.Dock = System.Windows.Forms.DockStyle.Fill
Me.RichTextBox1.Location = New System.Drawing.Point(0, 0)
Me.RichTextBox1.Name = "RichTextBox1"
Me.RichTextBox1.Size = New System.Drawing.Size(703, 459)
Me.RichTextBox1.TabIndex = 0
Me.RichTextBox1.Text = ""
'
'CodeForm
'
Me.ClientSize = New System.Drawing.Size(703, 459)
Me.Controls.Add(Me.RichTextBox1)
Me.Name = "CodeForm"
Me.Text = "CodeForm"
Me.ResumeLayout(False)
End Sub
Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
End Class
@@ -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,17 @@
Public Class CodeForm
'<SNIPPET1>
Public Property Code() As String
Get
If (RichTextBox1.Text IsNot Nothing) Then
Code = RichTextBox1.Text
Else
Code = ""
End If
End Get
Set(ByVal value As String)
RichTextBox1.Text = value
End Set
End Property
'</SNIPPET1>
End Class
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="utf-8"?>
<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>{BF207E8C-EBC4-4249-8D43-248022609973}</ProjectGuid>
<OutputType>WinExe</OutputType>
<StartupObject>DisplayWebBrowserCodeVB.My.MyApplication</StartupObject>
<RootNamespace>DisplayWebBrowserCodeVB</RootNamespace>
<AssemblyName>DisplayWebBrowserCodeVB</AssemblyName>
<MyType>WindowsForms</MyType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\</OutputPath>
<DocumentationFile>DisplayWebBrowserCodeVB.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032,42036</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DocumentationFile>DisplayWebBrowserCodeVB.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032,42036</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Drawing" />
<Import Include="System.Diagnostics" />
<Import Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeForm.Designer.vb">
<DependentUpon>CodeForm.vb</DependentUpon>
</Compile>
<Compile Include="CodeForm.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.vb">
<DependentUpon>Form1.vb</DependentUpon>
<SubType>Form</SubType>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\MyApplication.vb">
<AutoGen>True</AutoGen>
<DependentUpon>MyApplication.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\MyResources.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>MyResources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\MySettings.vb">
<AutoGen>True</AutoGen>
<DependentUpon>MySettings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="My Project\MyEvents.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="CodeForm.resx">
<DependentUpon>CodeForm.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="My Project\MyResources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>MyResources.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\MyApplication.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>MyApplication.vb</LastGenOutput>
</None>
<None Include="My Project\MySettings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>MySettings.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
</Project>
@@ -0,0 +1,70 @@
Partial Public Class Form1
Inherits System.Windows.Forms.Form
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.WebBrowser1 = New System.Windows.Forms.WebBrowser
Me.Button1 = New System.Windows.Forms.Button
Me.Button2 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'WebBrowser1
'
Me.WebBrowser1.Location = New System.Drawing.Point(12, 186)
Me.WebBrowser1.Name = "WebBrowser1"
Me.WebBrowser1.Size = New System.Drawing.Size(677, 250)
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(12, 12)
Me.Button1.Name = "Button1"
Me.Button1.TabIndex = 1
Me.Button1.Text = "Button1"
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(93, 12)
Me.Button2.Name = "Button2"
Me.Button2.TabIndex = 3
Me.Button2.Text = "Button2"
'
'Form1
'
Me.ClientSize = New System.Drawing.Size(701, 448)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.WebBrowser1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents WebBrowser1 As System.Windows.Forms.WebBrowser
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
End Class
@@ -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,18 @@
Public Class Form1
'<SNIPPET2>
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim elem As HtmlElement
If (WebBrowser1.Document IsNot Nothing) Then
Dim cf As New CodeForm()
Dim elems As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("HTML")
If (elems.Count = 1) Then
elem = elems(0)
cf.Code = elem.OuterHtml
cf.Show()
End If
End If
End Sub
'</SNIPPET2>
End Class
@@ -0,0 +1,34 @@
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("DisplayWebBrowserCodeVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("MS")>
<Assembly: AssemblyProduct("DisplayWebBrowserCodeVB")>
<Assembly: AssemblyCopyright("Copyright @ MS 2004")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("f8fed51f-5005-46ca-8086-3103ac36407b")>
' 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 Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="Windows-1252"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Form1</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>0</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
@@ -0,0 +1,30 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
Partial Class MyApplication
<Global.System.Diagnostics.DebuggerStepThrough()> Public Sub New()
MyBase.New(ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = False
Me.EnableVisualStyles = True
Me.SaveMySettingsOnExit = True
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThrough()> Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.DisplayWebBrowserCodeVB.Form1
End Sub
End Class
End Namespace
@@ -0,0 +1,15 @@
Namespace My
'Use the editor window dropdowns in the Application pane of the Project Designer to handle MyApplication Events
'
'Startup: Raised when the application starts, before the startup form is created.
'Shutdown: Raised after all application forms are closed. This event is not raised if the application is terminating abnormally.
'UnhandledException: Raised if the application encounters an unhandled exception.
'StartupNextInstance: Raised when launching a single-instance application and the application is already active.
'NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
End Class
End Namespace
@@ -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,61 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Imports System.IO
Imports System.Resources
Namespace My.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.
<Global.Microsoft.VisualBasic.HideModuleName()> _
Module MyResources
Private _resMgr As System.Resources.ResourceManager
Private _resCulture As System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> _
Public ReadOnly Property ResourceManager() As System.Resources.ResourceManager
Get
If (_resMgr Is Nothing) Then
Dim temp As System.Resources.ResourceManager = New System.Resources.ResourceManager("DisplayWebBrowserCodeVB.MyResources", GetType(MyResources).Assembly)
System.Threading.Thread.MemoryBarrier
_resMgr = temp
End If
Return _resMgr
End Get
End Property
'<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 Property Culture() As System.Globalization.CultureInfo
Get
Return _resCulture
End Get
Set
_resCulture = value
End Set
End Property
End Module
End Namespace
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,38 @@
'------------------------------------------------------------------------------
' <autogenerated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Partial Friend NotInheritable Class MySettings
Inherits System.Configuration.ApplicationSettingsBase
Private Shared m_Value As MySettings
Private Shared m_SyncObject As Object = New Object
<System.Diagnostics.DebuggerNonUserCode()> _
Public Shared ReadOnly Property Value() As MySettings
Get
If (MySettings.m_Value Is Nothing) Then
System.Threading.Monitor.Enter(MySettings.m_SyncObject)
If (MySettings.m_Value Is Nothing) Then
Try
MySettings.m_Value = New MySettings
Finally
System.Threading.Monitor.Exit(MySettings.m_SyncObject)
End Try
End If
End If
Return MySettings.m_Value
End Get
End Property
End Class
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log in Windows Forms projects.-->
<source name="Microsoft.VisualBasic.Logging.Log.WindowsFormsSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.1200.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
@@ -0,0 +1,301 @@
Option Explicit On
Option Strict On
Imports System.Diagnostics
Imports System.Windows.Forms
Imports System.Xml
Imports System.Data
Imports System.Collections
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class LinesCurvesAndShapes
Inherits Form
Dim myPen As Pen = Pens.Black
Dim mySolidBrush As SolidBrush = CType(Brushes.Red,SolidBrush)
Dim myGraphicsPath As New GraphicsPath()
<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New LinesCurvesAndShapes())
End Sub
' 0195df81-66be-452d-bb53-5a582ebfdc09
' Vector Graphics Overview
Public Sub Method11(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet11>
myGraphics.DrawRectangle(myPen, 20, 10, 100, 50)
' </snippet11>
End Sub
' 08d2cc9a-dc9d-4eed-bcbb-2c8e2ca5d3ae
' Open and Closed Curves in GDI+
Public Sub Method21(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet21>
myGraphics.FillPie(mySolidBrush, 0, 0, 140, 70, 0, 120)
myGraphics.DrawArc(myPen, 0, 0, 140, 70, 0, 120)
' </snippet21>
End Sub
Public Sub Method22(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet22>
Dim myPointArray As Point() = _
{New Point(0, 0), New Point(60, 20), New Point(40, 50)}
myGraphics.DrawClosedCurve(myPen, myPointArray)
myGraphics.FillClosedCurve(mySolidBrush, myPointArray)
' </snippet22>
End Sub
Public Sub Method23(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet23>
Dim mySolidBrush As New SolidBrush(Color.Aqua)
Dim myGraphicsPath As New GraphicsPath()
Dim myPointArray As Point() = { _
New Point(15, 20), _
New Point(20, 40), _
New Point(50, 30)}
Dim myFontFamily As New FontFamily("Times New Roman")
Dim myPointF As New PointF(50, 20)
Dim myStringFormat As 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>
End Sub
' 09b3797a-6294-422d-9adf-a5a0a7695c0c
' Cardinal Splines in GDI+
Public Sub Method31(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim myPointArray() As Point = New Point() {New Point(10, 10), _
New Point(50, 40), New Point(123, 200)}
' <snippet31>
myGraphics.DrawCurve(myPen, myPointArray, 1.5F)
' </snippet31>
End Sub
' 30b25aae-e3eb-4479-bdb8-187cf651fc84
' Pens, Lines, and Rectangles in GDI+
Public Sub Method41(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet41>
myGraphics.DrawLine(myPen, 4, 2, 12, 6)
' </snippet41>
End Sub
Public Sub Method42(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet42>
Dim myStartPoint As New Point(4, 2)
Dim myEndPoint As New Point(12, 6)
myGraphics.DrawLine(myPen, myStartPoint, myEndPoint)
' </snippet42>
End Sub
Public Sub Method43(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet43>
Dim myPen As New Pen(Color.Blue, 2)
myGraphics.DrawLine(myPen, 0, 0, 60, 30)
' </snippet43>
End Sub
Public Sub Method44(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet44>
myPen.DashStyle = DashStyle.Dash
myGraphics.DrawLine(myPen, 100, 50, 300, 80)
' </snippet44>
End Sub
Public Sub Method45(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet45>
myGraphics.DrawRectangle(myPen, 100, 50, 80, 40)
' </snippet45>
End Sub
Public Sub Method46(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet46>
Dim myRectangle As New Rectangle(100, 50, 80, 40)
myGraphics.DrawRectangle(myPen, myRectangle)
' </snippet46>
End Sub
' 34f35133-a835-4ca4-81f6-0dfedee8b683
' Ellipses and Arcs in GDI+
Public Sub Method51(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet51>
myGraphics.DrawEllipse(myPen, 100, 50, 80, 40)
' </snippet51>
End Sub
Public Sub Method52(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet52>
Dim myRectangle As New Rectangle(100, 50, 80, 40)
myGraphics.DrawEllipse(myPen, myRectangle)
' </snippet52>
End Sub
Public Sub Method53(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet53>
myGraphics.DrawArc(myPen, 100, 50, 140, 70, 30, 180)
' </snippet53>
End Sub
' 52184f9b-16dd-4bbd-85be-029112644ceb
' Regions in GDI+
Public Sub Method61(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim myRegion As New Region(Me.ClientRectangle)
' <snippet61>
myGraphics.FillRegion(mySolidBrush, myRegion)
' </snippet61>
End Sub
' 5774ce1e-87d4-4bc7-88c4-4862052781b8
' Bézier Splines in GDI+
Public Sub Method71(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet71>
myGraphics.DrawBezier(myPen, 0, 0, 40, 20, 80, 150, 100, 10)
' </snippet71>
End Sub
' 810da1a4-c136-4abf-88df-68e49efdd8d4
' Antialiasing with Lines and Curves
Public Sub Method81(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet81>
myGraphics.SmoothingMode = SmoothingMode.AntiAlias
myGraphics.DrawLine(myPen, 0, 0, 12, 8)
' </snippet81>
End Sub
' 8b5f71d9-d2f0-4540-9c41-740f90fd4c26
' Restricting the Drawing Surface in GDI+
Public Sub Method91(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim myRegion As New Region(Me.ClientRectangle)
' <snippet91>
myGraphics.Clip = myRegion
myGraphics.DrawLine(myPen, 0, 0, 200, 200)
' </snippet91>
End Sub
' a5500dec-666c-41fd-9da3-2169dd89c5eb
' Graphics Paths in GDI+
Public Sub Method101(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = 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>
End Sub
Public Sub Method102(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim graphicsPath1 As New GraphicsPath()
Dim graphicsPath2 As New GraphicsPath()
' <snippet102>
myGraphicsPath.AddPath(graphicsPath1, False)
myGraphicsPath.AddPath(graphicsPath2, False)
' </snippet102>
End Sub
Public Sub Method103(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet103>
Dim myGraphicsPath As New GraphicsPath()
Dim myPointArray As Point() = { _
New Point(5, 30), _
New Point(20, 40), _
New Point(50, 30)}
Dim myFontFamily As New FontFamily("Times New Roman")
Dim myPointF As New PointF(50, 20)
Dim myStringFormat As 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>
End Sub
' a72213d2-d69a-4c2b-a75c-be7b20390c13
' Polygons in GDI+
Public Sub Method111(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet111>
Dim myPointArray As Point() = _
{New Point(0, 0), New Point(50, 30), New Point(30, 60)}
myGraphics.DrawPolygon(myPen, myPointArray)
' </snippet111>
End Sub
' e863e2a7-0294-4130-99b6-f1ea3201e7cd
' Brushes and Filled Shapes in GDI+
Public Sub Method121(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet121>
Dim mySolidBrush As New SolidBrush(Color.Red)
myGraphics.FillEllipse(mySolidBrush, 0, 0, 60, 40)
' </snippet121>
End Sub
Public Sub Method122()
' <snippet122>
Dim myHatchBrush As _
New HatchBrush(HatchStyle.Vertical, Color.Blue, Color.Green)
' </snippet122>
End Sub
Public Sub Method123(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
' <snippet123>
Dim myImage As Image = Image.FromFile("MyTexture.bmp")
Dim myTextureBrush As New TextureBrush(myImage)
myGraphics.FillEllipse(myTextureBrush, 0, 0, 100, 50)
' </snippet123>
End Sub
Public Sub Method124(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim myRectangle As Rectangle = Me.ClientRectangle
' <snippet124>
Dim myLinearGradientBrush As New LinearGradientBrush( _
myRectangle, _
Color.Blue, _
Color.Green, _
LinearGradientMode.Horizontal)
myGraphics.FillEllipse(myLinearGradientBrush, myRectangle)
' </snippet124>
End Sub
End Class
@@ -0,0 +1,46 @@
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.WebBrowser1 = New System.Windows.Forms.WebBrowser
Me.SuspendLayout()
'
'WebBrowser1
'
Me.WebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill
Me.WebBrowser1.Location = New System.Drawing.Point(0, 0)
Me.WebBrowser1.Name = "WebBrowser1"
Me.WebBrowser1.Size = New System.Drawing.Size(623, 299)
Me.WebBrowser1.Url = New System.Uri("c:\userfiles\jayallen\ManagedDOMStyles\test.htm", System.UriKind.Absolute)
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(623, 299)
Me.Controls.Add(Me.WebBrowser1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents WebBrowser1 As System.Windows.Forms.WebBrowser
End Class
@@ -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,32 @@
'<SNIPPET2>
<System.Security.Permissions.PermissionSet(Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Public Class Form1
Dim SG As StyleGenerator = Nothing
Dim Elem As HtmlElement = Nothing
Dim WithEvents DocumentEvents As HtmlDocument
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
SG = New StyleGenerator()
DocumentEvents = WebBrowser1.Document
End Sub
Private Sub Document_MouseOver(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseOver
Elem = WebBrowser1.Document.GetElementFromPoint(e.MousePosition)
If Elem.TagName.Equals("DIV") Then
SG.ParseStyleString(Elem.Style)
SG.SetStyle("font-style", "italic")
Elem.Style = SG.GetStyleString()
End If
End Sub
Private Sub Document_MouseLeave(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseLeave
If (Elem IsNot Nothing) Then
SG.RemoveStyle("font-style")
Elem.Style = SG.GetStyleString()
' Reset, since we may mouse over a new DIV element next time.
SG.Clear()
End If
End Sub
End Class
'</SNIPPET2>
@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="utf-8"?>
<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>{E51D84AE-820E-4429-BF77-C7E728AD76E7}</ProjectGuid>
<OutputType>WinExe</OutputType>
<StartupObject>ManagedDOMStylesVB.My.MyApplication</StartupObject>
<RootNamespace>ManagedDOMStylesVB</RootNamespace>
<AssemblyName>ManagedDOMStylesVB</AssemblyName>
<MyType>WindowsForms</MyType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ManagedDOMStylesVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ManagedDOMStylesVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Drawing" />
<Import Include="System.Diagnostics" />
<Import Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.vb">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.vb">
<DependentUpon>Form1.vb</DependentUpon>
<SubType>Form</SubType>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="My Project\ApplicationEvents.vb" />
<Compile Include="StyleGenerator.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.vb</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.targets" />
</Project>
@@ -0,0 +1,37 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated, do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to project properties or double-click on the My Project node in the
' Solution Explorer), and make changes on the Application tab.
'
Partial Class MyApplication
<Global.System.Diagnostics.DebuggerStepThrough()> _
Public Sub New()
MyBase.New(Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThrough()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.ManagedDOMStylesVB.Form1
End Sub
End Class
End Namespace
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Form1</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>0</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
@@ -0,0 +1,15 @@
Namespace My
'The following events are available for MyApplication
'
'Startup: Raised when the application starts, before the startup form is created.
'Shutdown: Raised after all application forms are closed. This event is not raised if the application is terminating abnormally.
'UnhandledException: Raised if the application encounters an unhandled exception.
'StartupNextInstance: Raised when launching a single-instance application and the application is already active.
'NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Class MyApplication
End Class
End Namespace
@@ -0,0 +1,36 @@
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("ManagedDOMStylesVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("MS")>
<Assembly: AssemblyProduct("ManagedDOMStylesVB")>
<Assembly: AssemblyCopyright("Copyright © MS 2005")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("e035e2a2-2d20-4a80-8bbb-dc925cdd5ffe")>
' 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 Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
@@ -0,0 +1,64 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
<Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="My.Resources.Resources.get_ResourceManager():System.Resources.ResourceManager"), _
Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="My.Resources.Resources.get_Culture():System.Globalization.CultureInfo"), _
Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="My.Resources.Resources.set_Culture(System.Globalization.CultureInfo):Void")>
Namespace My.Resources
'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.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleName()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If (resourceMan Is Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ManagedDOMStylesVB.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<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)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
@@ -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,66 @@
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
<Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="ManagedDOMStylesVB.Settings.get_Default():ManagedDOMStylesVB.Settings"), _
Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="ManagedDOMStylesVB.My.MySettingsProperty.get_Settings():ManagedDOMStylesVB.Settings")>
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class Settings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As Settings = New Settings
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Object, ByVal e As EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As Settings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
#End If
Return defaultInstance
End Get
End Property
End Class
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.ManagedDOMStylesVB.Settings
Get
Return Global.ManagedDOMStylesVB.Settings.Default
End Get
End Property
End Module
End Namespace
@@ -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,90 @@
'<SNIPPET1>
Imports System.Collections.Generic
Imports System.Text
Public Class StyleGenerator
Dim styleDB As Dictionary(Of String, String)
Public Sub New()
styleDB = New Dictionary(Of String, String)()
End Sub
Public Function ContainsStyle(ByVal name As String) As Boolean
Return styleDB.ContainsKey(name)
End Function
Public Function SetStyle(ByVal name As String, ByVal value As String) As String
Dim oldValue As String = ""
If (Not name.Length > 0) Then
Throw New ArgumentException("Parameter name cannot be zero-length.")
End If
If (Not value.Length > 0) Then
Throw New ArgumentException("Parameter value cannot be zero-length.")
End If
If (styleDB.ContainsKey(name)) Then
oldValue = styleDB(name)
End If
styleDB(name) = value
Return oldValue
End Function
Public Function GetStyle(ByVal name As String) As String
If (Not name.Length > 0) Then
Throw New ArgumentException("Parameter name cannot be zero-length.")
End If
If (styleDB.ContainsKey(name)) Then
Return styleDB(name)
Else
Return ""
End If
End Function
Public Sub RemoveStyle(ByVal name As String)
If (styleDB.ContainsKey(name)) Then
styleDB.Remove(name)
End If
End Sub
Public Function GetStyleString() As String
If (styleDB.Count > 0) Then
Dim styleString As New StringBuilder("")
Dim key As String
For Each key In styleDB.Keys
styleString.Append(String.Format("{0}:{1};", CType(key, Object), CType(styleDB(key), Object)))
Next key
Return styleString.ToString()
Else
Return ""
End If
End Function
Public Sub ParseStyleString(ByVal styles As String)
If (styles.Length) > 0 Then
Dim stylePairs As String() = styles.Split(New Char() {";"c})
Dim stylePair As String
For Each stylePair In stylePairs
If (stylePairs.Length > 0) Then
Dim styleNameValue As String() = stylePair.Split(New Char() {":"c})
If (styleNameValue.Length = 2) Then
styleDB(styleNameValue(0)) = styleNameValue(1)
End If
End If
Next stylePair
End If
End Sub
Public Sub Clear()
styleDB.Clear()
End Sub
End Class
'</SNIPPET1>
@@ -0,0 +1,95 @@
Partial Public Class Form1
Inherits System.Windows.Forms.Form
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Me.firstName = New System.Windows.Forms.TextBox
Me.lastName = New System.Windows.Forms.TextBox
Me.PhoneMask = New System.Windows.Forms.MaskedTextBox
Me.NextButton = New System.Windows.Forms.Button
Me.PreviousButton = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'firstName
'
Me.firstName.Location = New System.Drawing.Point(26, 13)
Me.firstName.Name = "firstName"
Me.firstName.Size = New System.Drawing.Size(189, 20)
Me.firstName.TabIndex = 0
'
'lastName
'
Me.lastName.Location = New System.Drawing.Point(222, 13)
Me.lastName.Name = "lastName"
Me.lastName.Size = New System.Drawing.Size(207, 20)
Me.lastName.TabIndex = 1
'
'PhoneMask
'
Me.PhoneMask.Location = New System.Drawing.Point(436, 13)
Me.PhoneMask.Mask = "(009)-000-0000 x9999"
Me.PhoneMask.Name = "PhoneMask"
Me.PhoneMask.Size = New System.Drawing.Size(133, 20)
Me.PhoneMask.TabIndex = 2
'
'NextButton
'
Me.NextButton.Location = New System.Drawing.Point(685, 10)
Me.NextButton.Name = "NextButton"
Me.NextButton.Size = New System.Drawing.Size(104, 23)
Me.NextButton.TabIndex = 3
Me.NextButton.Text = "Next"
'
'PreviousButton
'
Me.PreviousButton.Location = New System.Drawing.Point(576, 10)
Me.PreviousButton.Name = "PreviousButton"
Me.PreviousButton.Size = New System.Drawing.Size(102, 23)
Me.PreviousButton.TabIndex = 4
Me.PreviousButton.Text = "Previous"
'
'Form1
'
Me.ClientSize = New System.Drawing.Size(840, 57)
Me.Controls.Add(Me.PreviousButton)
Me.Controls.Add(Me.NextButton)
Me.Controls.Add(Me.PhoneMask)
Me.Controls.Add(Me.lastName)
Me.Controls.Add(Me.firstName)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents firstName As System.Windows.Forms.TextBox
Friend WithEvents lastName As System.Windows.Forms.TextBox
Friend WithEvents PhoneMask As System.Windows.Forms.MaskedTextBox
Friend WithEvents NextButton As System.Windows.Forms.Button
Friend WithEvents PreviousButton As System.Windows.Forms.Button
End Class
@@ -0,0 +1,79 @@
'<SNIPPET1>
Imports System.Data.SqlClient
Public Class Form1
Dim WithEvents CurrentBinding, PhoneBinding As Binding
Dim EmployeesTable As New DataSet()
Dim sc As SqlConnection
Dim DataConnect As SqlDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DoMaskedBinding()
End Sub
Private Sub DoMaskedBinding()
Try
sc = New SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI")
sc.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
Application.Exit()
End Try
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")
PhoneMask.DataBindings.Add(PhoneBinding)
Catch ex As Exception
MessageBox.Show(ex.Message)
Application.Exit()
End Try
End Sub
Private Sub PhoneBinding_Format(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Format
Dim Ext As String
Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
If (CurrentRow("Extension") Is Nothing) Then
Ext = ""
Else
Ext = CurrentRow("Extension").ToString()
End If
e.Value = e.Value.ToString().Trim() & " x" & Ext
End Sub
Private Sub PhoneBinding_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Parse
Dim PhoneNumberAndExt As String = e.Value.ToString()
Dim ExtIndex As Integer = PhoneNumberAndExt.IndexOf("x")
Dim Ext As String = PhoneNumberAndExt.Substring(ExtIndex).Trim()
Dim PhoneNumber As String = PhoneNumberAndExt.Substring(0, ExtIndex).Trim()
' Get the current binding object, and set the new extension manually.
Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
' Remove the "x" from the extension.
CurrentRow("Extension") = CObj(Ext.Substring(1))
' Return the phone number.
e.Value = PhoneNumber
End Sub
Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click
Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position + 1
End Sub
Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click
Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position - 1
End Sub
End Class
'</SNIPPET1>
@@ -0,0 +1,2 @@
all:
vbc /t:library /out:mydll.dll Form1.Designer.vb form1.vb /imports:system.windows.forms,system.drawing,system.data
@@ -0,0 +1,983 @@
' <snippet10>
' <snippet11>
Imports System.Collections
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports System.Drawing
Imports System.Globalization
Imports System.Threading
Imports System.Windows.Forms
' </snippet11>
' This form tests the PrimeNumberCalculator component.
Public Class PrimeNumberCalculatorMain
Inherits System.Windows.Forms.Form
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Private fields
'
#Region "Private fields"
Private WithEvents primeNumberCalculator1 As PrimeNumberCalculator
Private taskGroupBox As System.Windows.Forms.GroupBox
Private WithEvents listView1 As System.Windows.Forms.ListView
Private taskIdColHeader As System.Windows.Forms.ColumnHeader
Private progressColHeader As System.Windows.Forms.ColumnHeader
Private currentColHeader As System.Windows.Forms.ColumnHeader
Private buttonPanel As System.Windows.Forms.Panel
Private panel2 As System.Windows.Forms.Panel
Private WithEvents startAsyncButton As System.Windows.Forms.Button
Private WithEvents cancelAsyncButton As System.Windows.Forms.Button
Private testNumberColHeader As System.Windows.Forms.ColumnHeader
Private resultColHeader As System.Windows.Forms.ColumnHeader
Private firstDivisorColHeader As System.Windows.Forms.ColumnHeader
Private components As System.ComponentModel.IContainer
Private progressCounter As Integer
Private progressInterval As Integer = 100
#End Region
Public Sub New()
InitializeComponent()
End Sub
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If (components IsNot Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#Region "Implementation"
' This event handler selects a number randomly to test
' for primality. It then starts the asynchronous
' calculation by calling the PrimeNumberCalculator
' component's CalculatePrimeAsync method.
Private Sub startAsyncButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles startAsyncButton.Click
' Randomly choose test numbers
' up to 200,000 for primality.
Dim rand As New Random
Dim testNumber As Integer = rand.Next(200000)
' Task IDs are Guids.
Dim taskId As Guid = Guid.NewGuid()
Me.AddListViewItem(taskId, testNumber)
' Start the asynchronous task.
Me.primeNumberCalculator1.CalculatePrimeAsync( _
testNumber, _
taskId)
End Sub
Private Sub listView1_SelectedIndexChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles listView1.SelectedIndexChanged
Me.cancelAsyncButton.Enabled = CanCancel()
End Sub
' This event handler cancels all pending tasks that are
' selected in the ListView control.
Private Sub cancelAsyncButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles cancelAsyncButton.Click
Dim taskId As Guid = Guid.Empty
' Cancel all selected tasks.
Dim lvi As ListViewItem
For Each lvi In Me.listView1.SelectedItems
' Tasks that have been completed or canceled have
' their corresponding ListViewItem.Tag property
' set to Nothing.
If (lvi.Tag IsNot Nothing) Then
taskId = CType(lvi.Tag, Guid)
Me.primeNumberCalculator1.CancelAsync(taskId)
lvi.Selected = False
End If
Next lvi
cancelAsyncButton.Enabled = False
End Sub
' <snippet40>
' This event handler updates the ListView control when the
' PrimeNumberCalculator raises the ProgressChanged event.
'
' On fast computers, the PrimeNumberCalculator can raise many
' successive ProgressChanged events, so the user interface
' may be flooded with messages. To prevent the user interface
' from hanging, progress is only reported at intervals.
Private Sub primeNumberCalculator1_ProgressChanged( _
ByVal e As ProgressChangedEventArgs) _
Handles primeNumberCalculator1.ProgressChanged
Me.progressCounter += 1
If Me.progressCounter Mod Me.progressInterval = 0 Then
Dim taskId As Guid = CType(e.UserState, Guid)
If TypeOf e Is CalculatePrimeProgressChangedEventArgs Then
Dim cppcea As CalculatePrimeProgressChangedEventArgs = e
Me.UpdateListViewItem( _
taskId, _
cppcea.ProgressPercentage, _
cppcea.LatestPrimeNumber)
Else
Me.UpdateListViewItem( _
taskId, e.ProgressPercentage)
End If
ElseIf Me.progressCounter > Me.progressInterval Then
Me.progressCounter = 0
End If
End Sub
' </snippet40>
' <snippet12>
' This event handler updates the ListView control when the
' PrimeNumberCalculator raises the CalculatePrimeCompleted
' event. The ListView item is updated with the appropriate
' outcome of the calculation: Canceled, Error, or result.
Private Sub primeNumberCalculator1_CalculatePrimeCompleted( _
ByVal sender As Object, _
ByVal e As CalculatePrimeCompletedEventArgs) _
Handles primeNumberCalculator1.CalculatePrimeCompleted
Dim taskId As Guid = CType(e.UserState, Guid)
If e.Cancelled Then
Dim result As String = "Canceled"
Dim lvi As ListViewItem = UpdateListViewItem( _
taskId, _
result)
If (lvi IsNot Nothing) Then
lvi.BackColor = Color.Pink
lvi.Tag = Nothing
End If
ElseIf e.Error IsNot Nothing Then
Dim result As String = "Error"
Dim lvi As ListViewItem = UpdateListViewItem( _
taskId, result)
If (lvi IsNot Nothing) Then
lvi.BackColor = Color.Red
lvi.ForeColor = Color.White
lvi.Tag = Nothing
End If
Else
Dim result As Boolean = e.IsPrime
Dim lvi As ListViewItem = UpdateListViewItem( _
taskId, _
result, _
e.FirstDivisor)
If (lvi IsNot Nothing) Then
lvi.BackColor = Color.LightGray
lvi.Tag = Nothing
End If
End If
End Sub
' </snippet12>
#End Region
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#Region "Private Methods"
Private Function AddListViewItem( _
ByVal guid As Guid, _
ByVal testNumber As Integer) As ListViewItem
Dim lvi As New ListViewItem
lvi.Text = testNumber.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lvi.SubItems.Add("Not Started")
lvi.SubItems.Add("1")
lvi.SubItems.Add(guid.ToString())
lvi.SubItems.Add("---")
lvi.SubItems.Add("---")
lvi.Tag = guid
Me.listView1.Items.Add(lvi)
Return lvi
End Function
Private Overloads Function UpdateListViewItem( _
ByVal guid As Guid, _
ByVal percentComplete As Integer, _
ByVal current As Integer) As ListViewItem
Dim lviRet As ListViewItem = Nothing
Dim lvi As ListViewItem
For Each lvi In Me.listView1.Items
If (lvi.Tag IsNot Nothing) Then
If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then
lvi.SubItems(1).Text = percentComplete.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lvi.SubItems(2).Text = current.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lviRet = lvi
Exit For
End If
End If
Next lvi
Return lviRet
End Function
Private Overloads Function UpdateListViewItem( _
ByVal guid As Guid, _
ByVal percentComplete As Integer, _
ByVal current As Integer, _
ByVal result As Boolean, _
ByVal firstDivisor As Integer) As ListViewItem
Dim lviRet As ListViewItem = Nothing
Dim lvi As ListViewItem
For Each lvi In Me.listView1.Items
If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then
lvi.SubItems(1).Text = percentComplete.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lvi.SubItems(2).Text = current.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lvi.SubItems(4).Text = _
IIf(result, "Prime", "Composite")
lvi.SubItems(5).Text = firstDivisor.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lviRet = lvi
Exit For
End If
Next lvi
Return lviRet
End Function
Private Overloads Function UpdateListViewItem( _
ByVal guid As Guid, _
ByVal percentComplete As Integer) As ListViewItem
Dim lviRet As ListViewItem = Nothing
Dim lvi As ListViewItem
For Each lvi In Me.listView1.Items
If (lvi.Tag IsNot Nothing) Then
If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then
lvi.SubItems(1).Text = percentComplete.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lviRet = lvi
Exit For
End If
End If
Next lvi
Return lviRet
End Function
Private Overloads Function UpdateListViewItem( _
ByVal guid As Guid, _
ByVal result As Boolean, _
ByVal firstDivisor As Integer) As ListViewItem
Dim lviRet As ListViewItem = Nothing
Dim lvi As ListViewItem
For Each lvi In Me.listView1.Items
If (lvi.Tag IsNot Nothing) Then
If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then
lvi.SubItems(4).Text = _
IIf(result, "Prime", "Composite")
lvi.SubItems(5).Text = firstDivisor.ToString( _
CultureInfo.CurrentCulture.NumberFormat)
lviRet = lvi
Exit For
End If
End If
Next lvi
Return lviRet
End Function
Private Overloads Function UpdateListViewItem( _
ByVal guid As Guid, _
ByVal result As String) As ListViewItem
Dim lviRet As ListViewItem = Nothing
Dim lvi As ListViewItem
For Each lvi In Me.listView1.Items
If (lvi.Tag IsNot Nothing) Then
If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then
lvi.SubItems(4).Text = result
lviRet = lvi
Exit For
End If
End If
Next lvi
Return lviRet
End Function
Private Function CanCancel() As Boolean
Dim oneIsActive As Boolean = False
Dim lvi As ListViewItem
For Each lvi In Me.listView1.SelectedItems
If (lvi.Tag IsNot Nothing) Then
oneIsActive = True
Exit For
End If
Next lvi
Return oneIsActive = True
End Function
#End Region
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.taskGroupBox = New System.Windows.Forms.GroupBox
Me.buttonPanel = New System.Windows.Forms.Panel
Me.cancelAsyncButton = New System.Windows.Forms.Button
Me.startAsyncButton = New System.Windows.Forms.Button
Me.listView1 = New System.Windows.Forms.ListView
Me.testNumberColHeader = New System.Windows.Forms.ColumnHeader
Me.progressColHeader = New System.Windows.Forms.ColumnHeader
Me.currentColHeader = New System.Windows.Forms.ColumnHeader
Me.taskIdColHeader = New System.Windows.Forms.ColumnHeader
Me.resultColHeader = New System.Windows.Forms.ColumnHeader
Me.firstDivisorColHeader = New System.Windows.Forms.ColumnHeader
Me.panel2 = New System.Windows.Forms.Panel
Me.primeNumberCalculator1 = New PrimeNumberCalculator(Me.components)
Me.taskGroupBox.SuspendLayout()
Me.buttonPanel.SuspendLayout()
Me.SuspendLayout()
'
' taskGroupBox
'
Me.taskGroupBox.Controls.Add(Me.buttonPanel)
Me.taskGroupBox.Controls.Add(Me.listView1)
Me.taskGroupBox.Dock = System.Windows.Forms.DockStyle.Fill
Me.taskGroupBox.Location = New System.Drawing.Point(0, 0)
Me.taskGroupBox.Name = "taskGroupBox"
Me.taskGroupBox.Size = New System.Drawing.Size(608, 254)
Me.taskGroupBox.TabIndex = 1
Me.taskGroupBox.TabStop = False
Me.taskGroupBox.Text = "Tasks"
'
' buttonPanel
'
Me.buttonPanel.Controls.Add(Me.cancelAsyncButton)
Me.buttonPanel.Controls.Add(Me.startAsyncButton)
Me.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom
Me.buttonPanel.Location = New System.Drawing.Point(3, 176)
Me.buttonPanel.Name = "buttonPanel"
Me.buttonPanel.Size = New System.Drawing.Size(602, 75)
Me.buttonPanel.TabIndex = 1
'
' cancelAsyncButton
'
Me.cancelAsyncButton.Enabled = False
Me.cancelAsyncButton.Location = New System.Drawing.Point(128, 24)
Me.cancelAsyncButton.Name = "cancelAsyncButton"
Me.cancelAsyncButton.Size = New System.Drawing.Size(88, 23)
Me.cancelAsyncButton.TabIndex = 1
Me.cancelAsyncButton.Text = "Cancel"
'
' startAsyncButton
'
Me.startAsyncButton.Location = New System.Drawing.Point(24, 24)
Me.startAsyncButton.Name = "startAsyncButton"
Me.startAsyncButton.Size = New System.Drawing.Size(88, 23)
Me.startAsyncButton.TabIndex = 0
Me.startAsyncButton.Text = "Start New Task"
'
' listView1
'
Me.listView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.testNumberColHeader, Me.progressColHeader, Me.currentColHeader, Me.taskIdColHeader, Me.resultColHeader, Me.firstDivisorColHeader})
Me.listView1.Dock = System.Windows.Forms.DockStyle.Fill
Me.listView1.FullRowSelect = True
Me.listView1.GridLines = True
Me.listView1.Location = New System.Drawing.Point(3, 16)
Me.listView1.Name = "listView1"
Me.listView1.Size = New System.Drawing.Size(602, 160)
Me.listView1.TabIndex = 0
Me.listView1.View = System.Windows.Forms.View.Details
'
' testNumberColHeader
'
Me.testNumberColHeader.Text = "Test Number"
Me.testNumberColHeader.Width = 80
'
' progressColHeader
'
Me.progressColHeader.Text = "Progress"
'
' currentColHeader
'
Me.currentColHeader.Text = "Current"
'
' taskIdColHeader
'
Me.taskIdColHeader.Text = "Task ID"
Me.taskIdColHeader.Width = 200
'
' resultColHeader
'
Me.resultColHeader.Text = "Result"
Me.resultColHeader.Width = 80
'
' firstDivisorColHeader
'
Me.firstDivisorColHeader.Text = "First Divisor"
Me.firstDivisorColHeader.Width = 80
'
' panel2
'
Me.panel2.Location = New System.Drawing.Point(200, 128)
Me.panel2.Name = "panel2"
Me.panel2.TabIndex = 2
'
' PrimeNumberCalculatorMain
'
Me.ClientSize = New System.Drawing.Size(608, 254)
Me.Controls.Add(taskGroupBox)
Me.Name = "PrimeNumberCalculatorMain"
Me.Text = "Prime Number Calculator"
Me.taskGroupBox.ResumeLayout(False)
Me.buttonPanel.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
<STAThread()> _
Shared Sub Main()
Application.Run(New PrimeNumberCalculatorMain())
End Sub
End Class
' <snippet30>
' <snippet7>
Public Delegate Sub ProgressChangedEventHandler( _
ByVal e As ProgressChangedEventArgs)
Public Delegate Sub CalculatePrimeCompletedEventHandler( _
ByVal sender As Object, _
ByVal e As CalculatePrimeCompletedEventArgs)
' </snippet7>
' This class implements the Event-based Asynchronous Pattern.
' It asynchronously computes whether a number is prime or
' composite (not prime).
Public Class PrimeNumberCalculator
Inherits System.ComponentModel.Component
' <snippet22>
Private Delegate Sub WorkerEventHandler( _
ByVal numberToCheck As Integer, _
ByVal asyncOp As AsyncOperation)
' </snippet22>
' <snippet9>
Private onProgressReportDelegate As SendOrPostCallback
Private onCompletedDelegate As SendOrPostCallback
' </snippet9>
' <snippet23>
Private userStateToLifetime As New HybridDictionary()
' </snippet23>
Private components As System.ComponentModel.Container = Nothing
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#Region "Public events"
' <snippet8>
Public Event ProgressChanged _
As ProgressChangedEventHandler
Public Event CalculatePrimeCompleted _
As CalculatePrimeCompletedEventHandler
' </snippet8>
#End Region
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#Region "Construction and destruction"
Public Sub New(ByVal container As System.ComponentModel.IContainer)
container.Add(Me)
InitializeComponent()
InitializeDelegates()
End Sub
' <snippet21>
Public Sub New()
InitializeComponent()
InitializeDelegates()
End Sub
' </snippet21>
' <snippet20>
Protected Overridable Sub InitializeDelegates()
onProgressReportDelegate = _
New SendOrPostCallback(AddressOf ReportProgress)
onCompletedDelegate = _
New SendOrPostCallback(AddressOf CalculateCompleted)
End Sub
' </snippet20>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If (components IsNot Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#End Region
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#Region "Implementation"
' <snippet3>
' This method starts an asynchronous calculation.
' First, it checks the supplied task ID for uniqueness.
' If taskId is unique, it creates a new WorkerEventHandler
' and calls its BeginInvoke method to start the calculation.
Public Overridable Sub CalculatePrimeAsync( _
ByVal numberToTest As Integer, _
ByVal taskId As Object)
' Create an AsyncOperation for taskId.
Dim asyncOp As AsyncOperation = _
AsyncOperationManager.CreateOperation(taskId)
' Multiple threads will access the task dictionary,
' so it must be locked to serialize access.
SyncLock userStateToLifetime.SyncRoot
If userStateToLifetime.Contains(taskId) Then
Throw New ArgumentException( _
"Task ID parameter must be unique", _
"taskId")
End If
userStateToLifetime(taskId) = asyncOp
End SyncLock
' Start the asynchronous operation.
Dim workerDelegate As New WorkerEventHandler( _
AddressOf CalculateWorker)
workerDelegate.BeginInvoke( _
numberToTest, _
asyncOp, _
Nothing, _
Nothing)
End Sub
' </snippet3>
' <snippet32>
' Utility method for determining if a
' task has been canceled.
Private Function TaskCanceled(ByVal taskId As Object) As Boolean
Return (userStateToLifetime(taskId) Is Nothing)
End Function
' </snippet32>
' <snippet4>
' This method cancels a pending asynchronous operation.
Public Sub CancelAsync(ByVal taskId As Object)
Dim obj As Object = userStateToLifetime(taskId)
If (obj IsNot Nothing) Then
SyncLock userStateToLifetime.SyncRoot
userStateToLifetime.Remove(taskId)
End SyncLock
End If
End Sub
' </snippet4>
' <snippet27>
' This method performs the actual prime number computation.
' It is executed on the worker thread.
Private Sub CalculateWorker( _
ByVal numberToTest As Integer, _
ByVal asyncOp As AsyncOperation)
Dim prime As Boolean = False
Dim firstDivisor As Integer = 1
Dim exc As Exception = Nothing
' Check that the task is still active.
' The operation may have been canceled before
' the thread was scheduled.
If Not Me.TaskCanceled(asyncOp.UserSuppliedState) Then
Try
' Find all the prime numbers up to the
' square root of numberToTest.
Dim primes As ArrayList = BuildPrimeNumberList( _
numberToTest, asyncOp)
' Now we have a list of primes less than
'numberToTest.
prime = IsPrime( _
primes, _
numberToTest, _
firstDivisor)
Catch ex As Exception
exc = ex
End Try
End If
Me.CompletionMethod( _
numberToTest, _
firstDivisor, _
prime, _
exc, _
TaskCanceled(asyncOp.UserSuppliedState), _
asyncOp)
End Sub
' </snippet27>
' <snippet5>
' This method computes the list of prime numbers used by the
' IsPrime method.
Private Function BuildPrimeNumberList( _
ByVal numberToTest As Integer, _
ByVal asyncOp As AsyncOperation) As ArrayList
Dim e As ProgressChangedEventArgs = Nothing
Dim primes As New ArrayList
Dim firstDivisor As Integer
Dim n As Integer = 5
' Add the first prime numbers.
primes.Add(2)
primes.Add(3)
' Do the work.
While n < numberToTest And _
Not Me.TaskCanceled(asyncOp.UserSuppliedState)
If IsPrime(primes, n, firstDivisor) Then
' Report to the client that you found a prime.
e = New CalculatePrimeProgressChangedEventArgs( _
n, _
CSng(n) / CSng(numberToTest) * 100, _
asyncOp.UserSuppliedState)
asyncOp.Post(Me.onProgressReportDelegate, e)
primes.Add(n)
' Yield the rest of this time slice.
Thread.Sleep(0)
End If
' Skip even numbers.
n += 2
End While
Return primes
End Function
' </snippet5>
' <snippet28>
' This method tests n for primality against the list of
' prime numbers contained in the primes parameter.
Private Function IsPrime( _
ByVal primes As ArrayList, _
ByVal n As Integer, _
ByRef firstDivisor As Integer) As Boolean
Dim foundDivisor As Boolean = False
Dim exceedsSquareRoot As Boolean = False
Dim i As Integer = 0
Dim divisor As Integer = 0
firstDivisor = 1
' Stop the search if:
' there are no more primes in the list,
' there is a divisor of n in the list, or
' there is a prime that is larger than
' the square root of n.
While i < primes.Count AndAlso _
Not foundDivisor AndAlso _
Not exceedsSquareRoot
' The divisor variable will be the smallest prime number
' not yet tried.
divisor = primes(i)
i = i + 1
' Determine whether the divisor is greater than the
' square root of n.
If divisor * divisor > n Then
exceedsSquareRoot = True
' Determine whether the divisor is a factor of n.
ElseIf n Mod divisor = 0 Then
firstDivisor = divisor
foundDivisor = True
End If
End While
Return Not foundDivisor
End Function
' </snippet28>
' <snippet24>
' This method is invoked via the AsyncOperation object,
' so it is guaranteed to be executed on the correct thread.
Private Sub CalculateCompleted(ByVal operationState As Object)
Dim e As CalculatePrimeCompletedEventArgs = operationState
OnCalculatePrimeCompleted(e)
End Sub
' This method is invoked via the AsyncOperation object,
' so it is guaranteed to be executed on the correct thread.
Private Sub ReportProgress(ByVal state As Object)
Dim e As ProgressChangedEventArgs = state
OnProgressChanged(e)
End Sub
Protected Sub OnCalculatePrimeCompleted( _
ByVal e As CalculatePrimeCompletedEventArgs)
RaiseEvent CalculatePrimeCompleted(Me, e)
End Sub
Protected Sub OnProgressChanged( _
ByVal e As ProgressChangedEventArgs)
RaiseEvent ProgressChanged(e)
End Sub
' </snippet24>
' <snippet26>
' This is the method that the underlying, free-threaded
' asynchronous behavior will invoke. This will happen on
' an arbitrary thread.
Private Sub CompletionMethod( _
ByVal numberToTest As Integer, _
ByVal firstDivisor As Integer, _
ByVal prime As Boolean, _
ByVal exc As Exception, _
ByVal canceled As Boolean, _
ByVal asyncOp As AsyncOperation)
' If the task was not previously canceled,
' remove the task from the lifetime collection.
If Not canceled Then
SyncLock userStateToLifetime.SyncRoot
userStateToLifetime.Remove(asyncOp.UserSuppliedState)
End SyncLock
End If
' Package the results of the operation in a
' CalculatePrimeCompletedEventArgs.
Dim e As New CalculatePrimeCompletedEventArgs( _
numberToTest, _
firstDivisor, _
prime, _
exc, _
canceled, _
asyncOp.UserSuppliedState)
' End the task. The asyncOp object is responsible
' for marshaling the call.
asyncOp.PostOperationCompleted(onCompletedDelegate, e)
' Note that after the call to PostOperationCompleted, asyncOp
' is no longer usable, and any attempt to use it will cause.
' an exception to be thrown.
End Sub
' </snippet26>
#End Region
Private Sub InitializeComponent()
End Sub
End Class
' <snippet29>
Public Class CalculatePrimeProgressChangedEventArgs
Inherits ProgressChangedEventArgs
Private latestPrimeNumberValue As Integer = 1
Public Sub New( _
ByVal latestPrime As Integer, _
ByVal progressPercentage As Integer, _
ByVal UserState As Object)
MyBase.New(progressPercentage, UserState)
Me.latestPrimeNumberValue = latestPrime
End Sub
Public ReadOnly Property LatestPrimeNumber() As Integer
Get
Return latestPrimeNumberValue
End Get
End Property
End Class
' </snippet29>
' <snippet6>
Public Class CalculatePrimeCompletedEventArgs
Inherits AsyncCompletedEventArgs
Private numberToTestValue As Integer = 0
Private firstDivisorValue As Integer = 1
Private isPrimeValue As Boolean
Public Sub New( _
ByVal numberToTest As Integer, _
ByVal firstDivisor As Integer, _
ByVal isPrime As Boolean, _
ByVal e As Exception, _
ByVal canceled As Boolean, _
ByVal state As Object)
MyBase.New(e, canceled, state)
Me.numberToTestValue = numberToTest
Me.firstDivisorValue = firstDivisor
Me.isPrimeValue = isPrime
End Sub
Public ReadOnly Property NumberToTest() As Integer
Get
' Raise an exception if the operation failed
' or was canceled.
RaiseExceptionIfNecessary()
' If the operation was successful, return
' the property value.
Return numberToTestValue
End Get
End Property
Public ReadOnly Property FirstDivisor() As Integer
Get
' Raise an exception if the operation failed
' or was canceled.
RaiseExceptionIfNecessary()
' If the operation was successful, return
' the property value.
Return firstDivisorValue
End Get
End Property
Public ReadOnly Property IsPrime() As Boolean
Get
' Raise an exception if the operation failed
' or was canceled.
RaiseExceptionIfNecessary()
' If the operation was successful, return
' the property value.
Return isPrimeValue
End Get
End Property
End Class
' </snippet6>
' </snippet30>
' </snippet10>
@@ -0,0 +1,549 @@
' <snippet1>
' <snippet2>
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Diagnostics
Imports System.Drawing
Imports System.Data
Imports System.Reflection
Imports System.Text
Imports 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.
Delegate Sub ThresholdExceededEventHandler(ByVal e As ThresholdExceededEventArgs)
' <snippet3>
' <snippet20>
' This control demonstrates a simple logging capability.
<ComplexBindingProperties("DataSource", "DataMember"), _
DefaultBindingProperty("TitleText"), _
DefaultEvent("ThresholdExceeded"), _
DefaultProperty("Threshold"), _
HelpKeywordAttribute(GetType(UserControl)), _
ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")> _
Public Class AttributesDemoControl
Inherits UserControl
' </snippet20>
' This backs the Threshold property.
Private thresholdValue As Object
' The default fore color value for DataGridView cells that
' contain values that exceed the threshold.
Private Shared defaultAlertForeColorValue As Color = Color.White
' The default back color value for DataGridView cells that
' contain values that exceed the threshold.
Private Shared defaultAlertBackColorValue As Color = Color.Red
' The ambient color value.
Private Shared ambientColorValue As Color = Color.Empty
' The fore color value for DataGridView cells that
' contain values that exceed the threshold.
Private alertForeColorValue As Color = defaultAlertForeColorValue
' The back color value for DataGridView cells that
' contain values that exceed the threshold.
Private alertBackColorValue As Color = defaultAlertBackColorValue
' Child controls that comprise this UserControl.
Private tableLayoutPanel1 As TableLayoutPanel
Private WithEvents dataGridView1 As DataGridView
Private label1 As Label
' Required for designer support.
Private components As System.ComponentModel.IContainer = Nothing
' Default constructor.
Public Sub New()
InitializeComponent()
End Sub
' <snippet21>
<Category("Appearance"), _
Description("The title of the log data."), _
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Localizable(True), _
HelpKeywordAttribute("AttributesDemoControlLibrary.AttributesDemoControl.TitleText")> _
Public Property TitleText() As String
Get
Return Me.label1.Text
End Get
Set(ByVal value As String)
Me.label1.Text = value
End Set
End Property
' </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 Overrides Property Text() As String
Get
Throw New NotSupportedException()
End Get
Set(ByVal value As String)
Throw New NotSupportedException()
End Set
End Property
' </snippet22>
' <snippet23>
<AmbientValue(GetType(Color), "Empty"), _
Category("Appearance"), _
DefaultValue(GetType(Color), "White"), _
Description("The color used for painting alert text.")> _
Public Property AlertForeColor() As Color
Get
If Me.alertForeColorValue = Color.Empty AndAlso (Me.Parent IsNot Nothing) Then
Return Parent.ForeColor
End If
Return Me.alertForeColorValue
End Get
Set(ByVal value As Color)
Me.alertForeColorValue = value
End Set
End Property
' This method is used by designers to enable resetting the
' property to its default value.
Public Sub ResetAlertForeColor()
Me.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue
End Sub
' 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 Function ShouldSerializeAlertForeColor() As Boolean
Return Me.alertForeColorValue <> AttributesDemoControl.ambientColorValue
End Function
' </snippet23>
' <snippet24>
<AmbientValue(GetType(Color), "Empty"), _
Category("Appearance"), _
DefaultValue(GetType(Color), "Red"), _
Description("The background color for painting alert text.")> _
Public Property AlertBackColor() As Color
Get
If Me.alertBackColorValue = Color.Empty AndAlso (Me.Parent IsNot Nothing) Then
Return Parent.BackColor
End If
Return Me.alertBackColorValue
End Get
Set(ByVal value As Color)
Me.alertBackColorValue = value
End Set
End Property
' This method is used by designers to enable resetting the
' property to its default value.
Public Sub ResetAlertBackColor()
Me.AlertBackColor = AttributesDemoControl.defaultAlertBackColorValue
End Sub
' 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 Function ShouldSerializeAlertBackColor() As Boolean
Return Me.alertBackColorValue <> AttributesDemoControl.ambientColorValue
End Function 'ShouldSerializeAlertBackColor
' </snippet24>
' <snippet25>
<Category("Data"), _
Description("Indicates the source of data for the control."), _
RefreshProperties(RefreshProperties.Repaint), _
AttributeProvider(GetType(IListSource))> _
Public Property DataSource() As Object
Get
Return Me.dataGridView1.DataSource
End Get
Set(ByVal value As Object)
Me.dataGridView1.DataSource = value
End Set
End Property
' </snippet25>
' <snippet26>
<Category("Data"), _
Description("Indicates a sub-list of the data source to show in the control.")> _
Public Property DataMember() As String
Get
Return Me.dataGridView1.DataMember
End Get
Set(ByVal value As String)
Me.dataGridView1.DataMember = value
End Set
End Property
' </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."), _
ReadOnlyAttribute(True)> _
Public Property CurrentLogTime() As DateTime
Get
Dim lastRowIndex As Integer = _
Me.dataGridView1.Rows.GetLastRow(DataGridViewElementStates.Visible)
If lastRowIndex > -1 Then
Dim lastRow As DataGridViewRow = Me.dataGridView1.Rows(lastRowIndex)
Dim lastCell As DataGridViewCell = lastRow.Cells("EntryTime")
Return CType(lastCell.Value, DateTime)
Else
Return DateTime.MinValue
End If
End Get
Set(ByVal value As DateTime)
End Set
End Property
' </snippet27>
' <snippet28>
<Category("Behavior"), _
Description("The value above which the ThresholdExceeded event will be raised.")> _
Public Property Threshold() As Object
Get
Return Me.thresholdValue
End Get
Set(ByVal value As Object)
Me.thresholdValue = value
End Set
End Property
' </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 ReadOnly Property Password() As String
Get
Return "This is a demo password."
End Get
End Property
' </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 ReadOnly Property MisnamedProperty() As Boolean
Get
Return True
End Get
End Property
' </snippet30>
' This is the declaration for the ThresholdExceeded event.
'Public Event ThresholdExceeded As ThresholdExceededEventHandler
Public Event ThresholdExceeded(ByVal e As ThresholdExceededEventArgs)
#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 Sub dataGridView1_CellFormatting( _
ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles dataGridView1.CellFormatting
Try
If (e.Value IsNot Nothing) Then
If TypeOf e.Value Is DateTime Then
' Display the log entry time with the
' full date/time pattern (long time).
e.CellStyle.Format = "F"
Else
' Scroll to the most recent entry.
Dim row As DataGridViewRow = Me.dataGridView1.Rows(e.RowIndex)
Dim cell As DataGridViewCell = row.Cells(e.ColumnIndex)
Me.dataGridView1.FirstDisplayedCell = cell
If (Me.thresholdValue IsNot Nothing) Then
' Get the type of the log entry.
Dim val As Object = e.Value
Dim paramType As Type = val.GetType()
' Compare the log entry value to the threshold value.
' Use reflection to call the CompareTo method on the
' template parameter's type.
Dim compareVal As Integer = _
Fix(paramType.InvokeMember("CompareTo", _
BindingFlags.Default Or BindingFlags.InvokeMethod, _
Nothing, _
e.Value, _
New Object() {Me.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 Then
e.CellStyle.BackColor = Me.alertBackColorValue
e.CellStyle.ForeColor = Me.alertForeColorValue
Dim teea As New ThresholdExceededEventArgs(Me.thresholdValue, e.Value)
RaiseEvent ThresholdExceeded(teea)
End If
End If
End If
End If
Catch ex As Exception
Trace.WriteLine(ex.Message)
End Try
End Sub
' </snippet31>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso (components IsNot Nothing) Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
Private Sub InitializeComponent()
Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle
Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel
Me.dataGridView1 = New System.Windows.Forms.DataGridView
Me.label1 = New System.Windows.Forms.Label
Me.tableLayoutPanel1.SuspendLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'tableLayoutPanel1
'
Me.tableLayoutPanel1.AutoSize = True
Me.tableLayoutPanel1.ColumnCount = 1
Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!))
Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!))
Me.tableLayoutPanel1.Controls.Add(Me.dataGridView1, 0, 1)
Me.tableLayoutPanel1.Controls.Add(Me.label1, 0, 0)
Me.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.tableLayoutPanel1.Location = New System.Drawing.Point(10, 10)
Me.tableLayoutPanel1.Name = "tableLayoutPanel1"
Me.tableLayoutPanel1.Padding = New System.Windows.Forms.Padding(10)
Me.tableLayoutPanel1.RowCount = 2
Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80.0!))
Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.tableLayoutPanel1.Size = New System.Drawing.Size(425, 424)
Me.tableLayoutPanel1.TabIndex = 0
'
'dataGridView1
'
Me.dataGridView1.AllowUserToAddRows = False
Me.dataGridView1.AllowUserToDeleteRows = False
Me.dataGridView1.AllowUserToOrderColumns = True
Me.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells
DataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control
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]
Me.dataGridView1.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle1
Me.dataGridView1.ColumnHeadersHeight = 4
Me.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill
Me.dataGridView1.Location = New System.Drawing.Point(13, 57)
Me.dataGridView1.Name = "dataGridView1"
Me.dataGridView1.ReadOnly = True
Me.dataGridView1.RowHeadersVisible = False
Me.dataGridView1.Size = New System.Drawing.Size(399, 354)
Me.dataGridView1.TabIndex = 1
'
'label1
'
Me.label1.AutoSize = True
Me.label1.BackColor = System.Drawing.SystemColors.Control
Me.label1.Dock = System.Windows.Forms.DockStyle.Fill
Me.label1.Location = New System.Drawing.Point(13, 13)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(399, 38)
Me.label1.TabIndex = 2
Me.label1.Text = "label1"
Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'AttributesDemoControl
'
Me.Controls.Add(Me.tableLayoutPanel1)
Me.Name = "AttributesDemoControl"
Me.Padding = New System.Windows.Forms.Padding(10)
Me.Size = New System.Drawing.Size(445, 444)
Me.tableLayoutPanel1.ResumeLayout(False)
Me.tableLayoutPanel1.PerformLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
' </snippet3>
' <snippet4>
' This is the EventArgs class for the ThresholdExceeded event.
Public Class ThresholdExceededEventArgs
Inherits EventArgs
Private thresholdVal As Object = Nothing
Private exceedingVal As Object = Nothing
Public Sub New(ByVal thresholdValue As Object, ByVal exceedingValue As Object)
Me.thresholdVal = thresholdValue
Me.exceedingVal = exceedingValue
End Sub
Public ReadOnly Property ThresholdValue() As Object
Get
Return Me.thresholdVal
End Get
End Property
Public ReadOnly Property ExceedingValue() As Object
Get
Return Me.exceedingVal
End Get
End Property
End Class
' </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(Of T As IComparable)
Private entryValue As T
Private entryTimeValue As DateTime
Public Sub New(ByVal value As T, ByVal time As DateTime)
Me.entryValue = value
Me.entryTimeValue = time
End Sub
Public ReadOnly Property Entry() As T
Get
Return Me.entryValue
End Get
End Property
Public ReadOnly Property EntryTime() As DateTime
Get
Return Me.entryTimeValue
End Get
End Property
' <snippet6>
' This is the TypeConverter for the LogEntry class.
Public Class LogEntryTypeConverter
Inherits TypeConverter
' <snippet7>
Public Overrides Function CanConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal sourceType As Type) As Boolean
If sourceType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertFrom(context, sourceType)
End Function
' </snippet7>
' <snippet8>
Public Overrides Function ConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal culture As System.Globalization.CultureInfo, _
ByVal value As Object) As Object
If TypeOf value Is String Then
Dim v As String() = CStr(value).Split(New Char() {"|"c})
Dim paramType As Type = GetType(T)
Dim entryValue As T = CType(paramType.InvokeMember("Parse", BindingFlags.Static Or BindingFlags.Public Or BindingFlags.InvokeMethod, Nothing, Nothing, New String() {v(0)}, culture), T)
Return New LogEntry(Of T)(entryValue, DateTime.Parse(v(2))) '
End If
Return MyBase.ConvertFrom(context, culture, value)
End Function
' </snippet8>
' <snippet9>
Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
If destinationType Is GetType(String) Then
Dim le As LogEntry(Of T) = CType(value, LogEntry(Of T))
Dim stringRepresentation As String = String.Format("{0} | {1}", le.Entry, le.EntryTime)
Return stringRepresentation
End If
Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function
End Class
' </snippet9>
End Class
' </snippet6>
' </snippet5>
End Namespace
' </snippet1>
@@ -0,0 +1,280 @@
' <snippet100>
' <snippet101>
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.Windows.Forms
Imports AttributesDemoControlLibrary
' </snippet101>
' This sample demonstrates using the AttributesDemoControl to log
' data from a data source.
Public Class Form1
Inherits Form
Private bindingSource1 As BindingSource
Private performanceCounter1 As System.Diagnostics.PerformanceCounter
Private WithEvents startButton As Button
Private WithEvents stopButton As Button
Private WithEvents timer1 As System.Timers.Timer
Private statusStrip1 As ToolStripStatusLabel
Private statusStripPanel1 As ToolStripStatusLabel
Private WithEvents numericUpDown1 As NumericUpDown
Private groupBox1 As GroupBox
Private groupBox2 As GroupBox
Private tableLayoutPanel1 As TableLayoutPanel
Private WithEvents attributesDemoControl1 As AttributesDemoControl
Private components As System.ComponentModel.IContainer = Nothing
' 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 Sub New()
InitializeComponent()
' Set the initial value of the threshold up/down control
' to the control's threshold value.
Me.numericUpDown1.Value = _
System.Convert.ToDecimal( _
System.Convert.ToSingle(Me.attributesDemoControl1.Threshold))
' Assign the performance counter's name to the control's
' title text.
Me.attributesDemoControl1.TitleText = _
Me.performanceCounter1.CounterName
End Sub
' This method handles the ThresholdExceeded event. It posts
' a the value that exceeded the threshold to the status strip.
Private Sub attributesDemoControl1_ThresholdExceeded( _
ByVal e As ThresholdExceededEventArgs) _
Handles attributesDemoControl1.ThresholdExceeded
Dim msg As String = String.Format( _
"{0}: Value {1} exceeded threshold {2}", _
Me.attributesDemoControl1.CurrentLogTime, _
e.ExceedingValue, _
e.ThresholdValue)
Me.ReportStatus(msg)
End Sub
' <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 Sub timer1_Elapsed( _
ByVal sender As Object, _
ByVal e As System.Timers.ElapsedEventArgs) _
Handles timer1.Elapsed
' Get the latest value from the performance counter.
Dim val As Single = Me.performanceCounter1.NextValue()
' The performance counter returns values of type float,
' but any type that implements the IComparable interface
' will work.
Dim entry As LogEntry(Of Single) = _
New LogEntry(Of Single)(val, DateTime.Now)
' Add the new LogEntry to the BindingSource list.
Me.bindingSource1.Add(entry)
End Sub
' </snippet110>
Private Sub numericUpDown1_ValueChanged( _
ByVal sender As Object, _
ByVal e As EventArgs) _
Handles numericUpDown1.ValueChanged
Me.attributesDemoControl1.Threshold = _
System.Convert.ToSingle(Me.numericUpDown1.Value)
Dim msg As String = String.Format( _
"Threshold changed to {0}", _
Me.attributesDemoControl1.Threshold)
Me.ReportStatus(msg)
End Sub
Private Sub startButton_Click( _
ByVal sender As Object, _
ByVal e As EventArgs) _
Handles startButton.Click
Me.ReportStatus((DateTime.Now.ToString() + ": Starting"))
Me.timer1.Start()
End Sub
Private Sub stopButton_Click( _
ByVal sender As Object, _
ByVal e As EventArgs) _
Handles stopButton.Click
Me.ReportStatus((DateTime.Now.ToString() + ": Stopping"))
Me.timer1.Stop()
End Sub
Private Sub ReportStatus(msg As String)
If (msg IsNot Nothing) Then
Me.statusStripPanel1.Text = msg
End If
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
Protected Overrides Sub Dispose(disposing As Boolean)
If disposing AndAlso (components IsNot Nothing) Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Me.bindingSource1 = New System.Windows.Forms.BindingSource(Me.components)
Me.performanceCounter1 = New System.Diagnostics.PerformanceCounter()
Me.startButton = New System.Windows.Forms.Button()
Me.stopButton = New System.Windows.Forms.Button()
Me.timer1 = New System.Timers.Timer()
Me.statusStripPanel1 = New System.Windows.Forms.ToolStripStatusLabel()
Me.numericUpDown1 = New System.Windows.Forms.NumericUpDown()
Me.groupBox1 = New System.Windows.Forms.GroupBox()
Me.groupBox2 = New System.Windows.Forms.GroupBox()
Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
Me.attributesDemoControl1 = New AttributesDemoControlLibrary.AttributesDemoControl()
CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.performanceCounter1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.timer1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.groupBox1.SuspendLayout()
Me.groupBox2.SuspendLayout()
Me.tableLayoutPanel1.SuspendLayout()
Me.SuspendLayout()
'
' performanceCounter1
'
Me.performanceCounter1.CategoryName = ".NET CLR Memory"
Me.performanceCounter1.CounterName = "Gen 0 heap size"
Me.performanceCounter1.InstanceName = "_Global_"
'
' startButton
'
Me.startButton.Location = New System.Drawing.Point(31, 25)
Me.startButton.Name = "startButton"
Me.startButton.TabIndex = 1
Me.startButton.Text = "Start"
'
' stopButton
'
Me.stopButton.Location = New System.Drawing.Point(112, 25)
Me.stopButton.Name = "stopButton"
Me.stopButton.TabIndex = 2
Me.stopButton.Text = "Stop"
'
' timer1
'
Me.timer1.Interval = 1000
Me.timer1.SynchronizingObject = Me
'
' statusStripPanel1
'
Me.statusStripPanel1.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter
Me.statusStripPanel1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text
Me.statusStripPanel1.Name = "statusStripPanel1"
Me.statusStripPanel1.Text = "Ready"
'
' numericUpDown1
'
Me.numericUpDown1.Location = New System.Drawing.Point(37, 29)
Me.numericUpDown1.Maximum = New Decimal(New Integer() {1410065408, 2, 0, 0})
Me.numericUpDown1.Name = "numericUpDown1"
Me.numericUpDown1.TabIndex = 7
'
' groupBox1
'
Me.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.None
Me.groupBox1.Controls.Add(Me.numericUpDown1)
Me.groupBox1.Location = New System.Drawing.Point(280, 326)
Me.groupBox1.Name = "groupBox1"
Me.groupBox1.Size = New System.Drawing.Size(200, 70)
Me.groupBox1.TabIndex = 13
Me.groupBox1.TabStop = False
Me.groupBox1.Text = "Threshold Value"
'
' groupBox2
'
Me.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None
Me.groupBox2.Controls.Add(Me.startButton)
Me.groupBox2.Controls.Add(Me.stopButton)
Me.groupBox2.Location = New System.Drawing.Point(26, 327)
Me.groupBox2.Name = "groupBox2"
Me.groupBox2.Size = New System.Drawing.Size(214, 68)
Me.groupBox2.TabIndex = 14
Me.groupBox2.TabStop = False
Me.groupBox2.Text = "Logging"
'
' tableLayoutPanel1
'
Me.tableLayoutPanel1.ColumnCount = 2
Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F))
Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F))
Me.tableLayoutPanel1.Controls.Add(Me.groupBox2, 0, 1)
Me.tableLayoutPanel1.Controls.Add(Me.groupBox1, 1, 1)
Me.tableLayoutPanel1.Controls.Add(Me.attributesDemoControl1, 0, 0)
Me.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.tableLayoutPanel1.Location = New System.Drawing.Point(0, 0)
Me.tableLayoutPanel1.Name = "tableLayoutPanel1"
Me.tableLayoutPanel1.Padding = New System.Windows.Forms.Padding(10)
Me.tableLayoutPanel1.RowCount = 2
Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F))
Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F))
Me.tableLayoutPanel1.Size = New System.Drawing.Size(514, 411)
Me.tableLayoutPanel1.TabIndex = 15
'
' attributesDemoControl1
'
Me.tableLayoutPanel1.SetColumnSpan(Me.attributesDemoControl1, 2)
Me.attributesDemoControl1.DataMember = ""
Me.attributesDemoControl1.DataSource = Me.bindingSource1
Me.attributesDemoControl1.Dock = System.Windows.Forms.DockStyle.Fill
Me.attributesDemoControl1.Location = New System.Drawing.Point(13, 13)
Me.attributesDemoControl1.Name = "attributesDemoControl1"
Me.attributesDemoControl1.Padding = New System.Windows.Forms.Padding(10)
Me.attributesDemoControl1.Size = New System.Drawing.Size(488, 306)
Me.attributesDemoControl1.TabIndex = 0
Me.attributesDemoControl1.Threshold = 200000F
Me.attributesDemoControl1.TitleText = "TITLE"
'
' Form1
'
Me.BackColor = System.Drawing.SystemColors.Control
Me.ClientSize = New System.Drawing.Size(514, 430)
Me.Controls.Add(tableLayoutPanel1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.performanceCounter1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.timer1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
Me.groupBox1.ResumeLayout(False)
Me.groupBox2.ResumeLayout(False)
Me.tableLayoutPanel1.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
End Class
' </snippet100>
@@ -0,0 +1,10 @@
all: AttributesDemoControl.dll form1.exe
AttributesDemoControl.dll: AttributesDemoControl.vb
vbc /target:library AttributesDemoControl.vb
Form1.exe: AttributesDemoControl.dll
vbc form1.vb /r:AttributesDemoControl.dll
clean:
del *.exe *.dll *.bin *.obj
@@ -0,0 +1,210 @@
' <snippet1>
' <snippet7>
Imports System.ComponentModel
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms
' </snippet7>
Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
' <snippet2>
Private Sub backgroundWorker1_DoWork( _
sender As Object, e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork
' Do not access the form's BackgroundWorker reference directly.
' Instead, use the reference provided by the sender parameter.
Dim bw As BackgroundWorker = CType( sender, BackgroundWorker )
' Extract the argument.
Dim arg As Integer = Fix(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 Then
e.Cancel = True
End If
End Sub
' </snippet2>
' <snippet3>
' This event handler demonstrates how to interpret
' the outcome of the asynchronous operation implemented
' in the DoWork event handler.
Private Sub backgroundWorker1_RunWorkerCompleted( _
sender As Object, e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
' The user canceled the operation.
MessageBox.Show("Operation was canceled")
ElseIf (e.Error IsNot Nothing) Then
' There was an error during the operation.
Dim msg As String = String.Format("An error occurred: {0}", e.Error.Message)
MessageBox.Show(msg)
Else
' The operation completed normally.
Dim msg As String = String.Format("Result = {0}", e.Result)
MessageBox.Show(msg)
End If
End Sub
' </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 Function TimeConsumingOperation( _
bw As BackgroundWorker, _
sleepPeriod As Integer) As Integer
Dim result As Integer = 0
Dim rand As New Random()
While Not bw.CancellationPending
Dim [exit] As Boolean = False
Select Case rand.Next(3)
' Raise an exception.
Case 0
Throw New Exception("An error condition occurred.")
Exit While
' Sleep for the number of milliseconds
' specified by the sleepPeriod parameter.
Case 1
Thread.Sleep(sleepPeriod)
Exit While
' Exit and return normally.
Case 2
result = 23
[exit] = True
Exit While
Case Else
Exit While
End Select
If [exit] Then
Exit While
End If
End While
Return result
End Function
' </snippet4>
' <snippet5>
Private Sub startButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles startBtn.Click
Me.backgroundWorker1.RunWorkerAsync(2000)
End Sub
' </snippet5>
' <snippet6>
Private Sub cancelButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cancelBtn.Click
Me.backgroundWorker1.CancelAsync()
End Sub
' </snippet6>
' <summary>
' Required designer variable.
' </summary>
Private components As System.ComponentModel.IContainer = Nothing
' <summary>
' Clean up any resources being used.
' </summary>
' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso (components IsNot Nothing) Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
#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 Sub InitializeComponent()
Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker()
Me.startBtn = New System.Windows.Forms.Button()
Me.cancelBtn = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
' backgroundWorker1
'
Me.backgroundWorker1.WorkerSupportsCancellation = True
'
' startButton
'
Me.startBtn.Location = New System.Drawing.Point(12, 12)
Me.startBtn.Name = "startButton"
Me.startBtn.Size = New System.Drawing.Size(75, 23)
Me.startBtn.TabIndex = 0
Me.startBtn.Text = "Start"
'
' cancelButton
'
Me.cancelBtn.Location = New System.Drawing.Point(94, 11)
Me.cancelBtn.Name = "cancelButton"
Me.cancelBtn.Size = New System.Drawing.Size(75, 23)
Me.cancelBtn.TabIndex = 1
Me.cancelBtn.Text = "Cancel"
'
' Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(183, 49)
Me.Controls.Add(cancelBtn)
Me.Controls.Add(startBtn)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
Private WithEvents backgroundWorker1 As System.ComponentModel.BackgroundWorker
Private WithEvents startBtn As System.Windows.Forms.Button
Private WithEvents cancelBtn As System.Windows.Forms.Button
End Class
Public Class Program
Private Sub New()
End Sub
' <summary>
' The main entry point for the application.
' </summary>
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
' </snippet1>
@@ -0,0 +1,159 @@
' <snippet1>
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms
Imports System.Xml
Public Class Form1
Inherits Form
Private WithEvents downloadButton As Button
Private WithEvents progressBar1 As ProgressBar
Private WithEvents backgroundWorker1 As BackgroundWorker
Private document As XmlDocument = Nothing
Public Sub New()
InitializeComponent()
Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker()
End Sub
' <snippet2>
Private Sub downloadButton_Click( _
ByVal sender As Object, _
ByVal e As EventArgs) _
Handles downloadButton.Click
' Start the download operation in the background.
Me.backgroundWorker1.RunWorkerAsync()
' Disable the button for the duration of the download.
Me.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.
' 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 Me.backgroundWorker1.IsBusy
progressBar1.Increment(1)
' Keep UI messages moving, so the form remains
' responsive during the asynchronous operation.
Application.DoEvents()
End While
End Sub
' </snippet2>
' <snippet3>
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork
document = New XmlDocument()
' Replace this file name with a valid file name.
document.Load("http://www.tailspintoys.com/sample.xml")
' Uncomment the following line to
' simulate a noticeable latency.
'Thread.Sleep(5000);
End Sub
' </snippet3>
' <snippet4>
Private Sub backgroundWorker1_RunWorkerCompleted( _
ByVal sender As Object, _
ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted
' Set progress bar to 100% in case it isn't already there.
progressBar1.Value = 100
If e.Error Is Nothing Then
MessageBox.Show(document.InnerXml, "Download Complete")
Else
MessageBox.Show("Failed to download file", "Download failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
' Enable the download button and reset the progress bar.
Me.downloadButton.Enabled = True
progressBar1.Value = 0
End Sub
' </snippet4>
#Region "Windows Form Designer generated code"
' <summary>
' Required designer variable.
' </summary>
Private components As System.ComponentModel.IContainer = Nothing
' <summary>
' Clean up any resources being used.
' </summary>
' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso (components IsNot Nothing) Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
' <summary>
' Required method for Designer support - do not modify
' the contents of this method with the code editor.
' </summary>
Private Sub InitializeComponent()
Me.downloadButton = New System.Windows.Forms.Button
Me.progressBar1 = New System.Windows.Forms.ProgressBar
Me.SuspendLayout()
'
'downloadButton
'
Me.downloadButton.Location = New System.Drawing.Point(12, 12)
Me.downloadButton.Name = "downloadButton"
Me.downloadButton.Size = New System.Drawing.Size(100, 23)
Me.downloadButton.TabIndex = 0
Me.downloadButton.Text = "Download file"
Me.downloadButton.UseVisualStyleBackColor = True
'
'progressBar1
'
Me.progressBar1.Location = New System.Drawing.Point(12, 50)
Me.progressBar1.Name = "progressBar1"
Me.progressBar1.Size = New System.Drawing.Size(100, 26)
Me.progressBar1.TabIndex = 1
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(136, 104)
Me.Controls.Add(Me.downloadButton)
Me.Controls.Add(Me.progressBar1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
End Class
Public Class Program
' <summary>
' The main entry point for the application.
' </summary>
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
' </snippet1>
@@ -0,0 +1,282 @@
' <snippet1>
' <snippet2>
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms
' </snippet2>
Public Class FibonacciForm
Inherits System.Windows.Forms.Form
' <snippet14>
Private numberToCompute As Integer = 0
Private highestPercentageReached As Integer = 0
' </snippet14>
Private numericUpDown1 As System.Windows.Forms.NumericUpDown
Private WithEvents startAsyncButton As System.Windows.Forms.Button
Private WithEvents cancelAsyncButton As System.Windows.Forms.Button
Private progressBar1 As System.Windows.Forms.ProgressBar
Private resultLabel As System.Windows.Forms.Label
Private WithEvents backgroundWorker1 As System.ComponentModel.BackgroundWorker
Public Sub New()
InitializeComponent()
End Sub
' <snippet13>
Private Sub startAsyncButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles startAsyncButton.Click
' Reset the text in the result label.
resultLabel.Text = [String].Empty
' Disable the UpDown control until
' the asynchronous operation is done.
Me.numericUpDown1.Enabled = False
' Disable the Start button until
' the asynchronous operation is done.
Me.startAsyncButton.Enabled = False
' Enable the Cancel button while
' the asynchronous operation runs.
Me.cancelAsyncButton.Enabled = True
' Get the value from the UpDown control.
numberToCompute = CInt(numericUpDown1.Value)
' Reset the variable for percentage tracking.
highestPercentageReached = 0
' <snippet3>
' Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(numberToCompute)
' </snippet3>
End Sub
' </snippet13>
' <snippet4>
Private Sub cancelAsyncButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles cancelAsyncButton.Click
' Cancel the asynchronous operation.
Me.backgroundWorker1.CancelAsync()
' Disable the Cancel button.
cancelAsyncButton.Enabled = False
End Sub
' </snippet4>
' <snippet5>
' This event handler is where the actual work is done.
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork
' Get the BackgroundWorker object that raised this event.
Dim worker As BackgroundWorker = _
CType(sender, 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(e.Argument, worker, e)
End Sub
' </snippet5>
' <snippet6>
' This event handler deals with the results of the
' background operation.
Private Sub backgroundWorker1_RunWorkerCompleted( _
ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted
' First, handle the case where an exception was thrown.
If (e.Error IsNot Nothing) Then
MessageBox.Show(e.Error.Message)
ElseIf e.Cancelled Then
' 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()
End If
' Enable the UpDown control.
Me.numericUpDown1.Enabled = True
' Enable the Start button.
startAsyncButton.Enabled = True
' Disable the Cancel button.
cancelAsyncButton.Enabled = False
End Sub
' </snippet6>
' <snippet7>
' This event handler updates the progress bar.
Private Sub backgroundWorker1_ProgressChanged( _
ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
Handles backgroundWorker1.ProgressChanged
Me.progressBar1.Value = e.ProgressPercentage
End Sub
' </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.
Function ComputeFibonacci( _
ByVal n As Integer, _
ByVal worker As BackgroundWorker, _
ByVal e As DoWorkEventArgs) As Long
' The parameter n must be >= 0 and <= 91.
' Fib(n), with n > 91, overflows a long.
If n < 0 OrElse n > 91 Then
Throw New ArgumentException( _
"value must be >= 0 and <= 91", "n")
End If
Dim result As Long = 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 Then
e.Cancel = True
' </snippet11>
Else
If n < 2 Then
result = 1
Else
result = ComputeFibonacci(n - 1, worker, e) + _
ComputeFibonacci(n - 2, worker, e)
End If
' <snippet12>
' Report progress as a percentage of the total task.
Dim percentComplete As Integer = _
CSng(n) / CSng(numberToCompute) * 100
If percentComplete > highestPercentageReached Then
highestPercentageReached = percentComplete
worker.ReportProgress(percentComplete)
End If
' </snippet12>
End If
' </snippet8>
Return result
End Function
' </snippet10>
Private Sub InitializeComponent()
Me.numericUpDown1 = New System.Windows.Forms.NumericUpDown
Me.startAsyncButton = New System.Windows.Forms.Button
Me.cancelAsyncButton = New System.Windows.Forms.Button
Me.resultLabel = New System.Windows.Forms.Label
Me.progressBar1 = New System.Windows.Forms.ProgressBar
Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker
CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'numericUpDown1
'
Me.numericUpDown1.Location = New System.Drawing.Point(16, 16)
Me.numericUpDown1.Maximum = New Decimal(New Integer() {91, 0, 0, 0})
Me.numericUpDown1.Minimum = New Decimal(New Integer() {1, 0, 0, 0})
Me.numericUpDown1.Name = "numericUpDown1"
Me.numericUpDown1.Size = New System.Drawing.Size(80, 20)
Me.numericUpDown1.TabIndex = 0
Me.numericUpDown1.Value = New Decimal(New Integer() {1, 0, 0, 0})
'
'startAsyncButton
'
Me.startAsyncButton.Location = New System.Drawing.Point(16, 72)
Me.startAsyncButton.Name = "startAsyncButton"
Me.startAsyncButton.Size = New System.Drawing.Size(120, 23)
Me.startAsyncButton.TabIndex = 1
Me.startAsyncButton.Text = "Start Async"
'
'cancelAsyncButton
'
Me.cancelAsyncButton.Enabled = False
Me.cancelAsyncButton.Location = New System.Drawing.Point(153, 72)
Me.cancelAsyncButton.Name = "cancelAsyncButton"
Me.cancelAsyncButton.Size = New System.Drawing.Size(119, 23)
Me.cancelAsyncButton.TabIndex = 2
Me.cancelAsyncButton.Text = "Cancel Async"
'
'resultLabel
'
Me.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.resultLabel.Location = New System.Drawing.Point(112, 16)
Me.resultLabel.Name = "resultLabel"
Me.resultLabel.Size = New System.Drawing.Size(160, 23)
Me.resultLabel.TabIndex = 3
Me.resultLabel.Text = "(no result)"
Me.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'progressBar1
'
Me.progressBar1.Location = New System.Drawing.Point(18, 48)
Me.progressBar1.Name = "progressBar1"
Me.progressBar1.Size = New System.Drawing.Size(256, 8)
Me.progressBar1.TabIndex = 4
'
'backgroundWorker1
'
Me.backgroundWorker1.WorkerReportsProgress = True
Me.backgroundWorker1.WorkerSupportsCancellation = True
'
'FibonacciForm
'
Me.ClientSize = New System.Drawing.Size(292, 118)
Me.Controls.Add(Me.progressBar1)
Me.Controls.Add(Me.resultLabel)
Me.Controls.Add(Me.cancelAsyncButton)
Me.Controls.Add(Me.startAsyncButton)
Me.Controls.Add(Me.numericUpDown1)
Me.Name = "FibonacciForm"
Me.Text = "Fibonacci Calculator"
CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
<STAThread()> _
Shared Sub Main()
Application.Run(New FibonacciForm)
End Sub
End Class
' </snippet1>
@@ -0,0 +1,125 @@
' <snippet1>
' <snippet2>
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
' </snippet2>
' This sample demonstrates the use of the
' DesignerSerializationVisibility attribute
' to serialize a collection of strings
' at design time.
Class Form1
Inherits Form
Private serializationDemoControl1 As SerializationDemoControl
Public Sub New()
InitializeComponent()
End Sub
' 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 Sub InitializeComponent()
Me.serializationDemoControl1 = New SerializationDemoControl
Me.SuspendLayout()
'
'serializationDemoControl1
'
Me.serializationDemoControl1.Location = New System.Drawing.Point(0, 0)
Me.serializationDemoControl1.Name = "serializationDemoControl1"
Me.serializationDemoControl1.Padding = New System.Windows.Forms.Padding(5)
Me.serializationDemoControl1.TabIndex = 0
'
'Form1
'
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Controls.Add(Me.serializationDemoControl1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
' <snippet3>
Public Class SerializationDemoControl
Inherits UserControl
' This is the TextBox contained by
' the SerializationDemoControl.
Private textBox1 As System.Windows.Forms.TextBox
' <snippet4>
' This field backs the Strings property.
Private stringsValue(1) As String
' </snippet4>
Public Sub New()
InitializeComponent()
End Sub
' <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 Property Strings() As String()
Get
Return Me.stringsValue
End Get
Set(ByVal value As String())
Me.stringsValue = Value
' Populate the contained TextBox with the values
' in the stringsValue array.
Dim sb As New StringBuilder(Me.stringsValue.Length)
Dim i As Integer
For i = 0 To (Me.stringsValue.Length) - 1
sb.Append(Me.stringsValue(i))
sb.Append(ControlChars.Cr + ControlChars.Lf)
Next i
Me.textBox1.Text = sb.ToString()
End Set
End Property
' </snippet5>
Private Sub InitializeComponent()
Me.textBox1 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
' Settings for the contained TextBox control.
Me.textBox1.AutoSize = False
Me.textBox1.Dock = System.Windows.Forms.DockStyle.Fill
Me.textBox1.Location = New System.Drawing.Point(5, 5)
Me.textBox1.Margin = New System.Windows.Forms.Padding(0)
Me.textBox1.Multiline = True
Me.textBox1.Name = "textBox1"
Me.textBox1.ReadOnly = True
Me.textBox1.ScrollBars = ScrollBars.Vertical
Me.textBox1.Size = New System.Drawing.Size(140, 140)
Me.textBox1.TabIndex = 0
' Settings for SerializationDemoControl.
Me.Controls.Add(textBox1)
Me.Name = "SerializationDemoControl"
Me.Padding = New System.Windows.Forms.Padding(5)
Me.ResumeLayout(False)
End Sub
End Class
' </snippet3>
' </snippet1>
@@ -0,0 +1,22 @@
' <snippet100>
Imports System.ComponentModel
Public Class BusinessObjectBase
Implements INotifyPropertyChanged
#Region "INotifyPropertyChanged Members"
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String)
OnPropertyChanged(New PropertyChangedEventArgs(propertyName))
End Sub
Private Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)
RaiseEvent PropertyChanged(Me, e)
End Sub
#End Region
End Class
' </snippet100>
@@ -0,0 +1,54 @@
' <snippet10>
Imports System.ComponentModel
Public Class Employee
Inherits BusinessObjectBase
Private _id As String
Private _name As String
Private _parkingId As Decimal
Public Sub New(ByVal name As String, ByVal parkId As Decimal)
MyBase.New()
Me._id = System.Guid.NewGuid().ToString()
' Set values
Me.Name = name
Me.ParkingID = parkId
End Sub
Public ReadOnly Property ID() As String
Get
Return _id
End Get
End Property
Const NAME_Const As String = "Name"
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
If _name <> value Then
_name = value
OnPropertyChanged(NAME_Const)
End If
End Set
End Property
Const PARKINGID_Const As String = "ParkingID"
Public Property ParkingID() As Decimal
Get
Return _parkingId
End Get
Set(ByVal value As Decimal)
If _parkingId <> value Then
_parkingId = value
OnPropertyChanged(PARKINGID_Const)
End If
End Set
End Property
End Class
' </snippet10>
@@ -0,0 +1,80 @@
' <snippet1>
Imports System.ComponentModel
Public Class EmployeeListSource
Inherits Component
Implements IListSource
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New(ByVal Container As System.ComponentModel.IContainer)
MyClass.New()
'Required for Windows.Forms Class Composition Designer support
Container.Add(Me)
End Sub
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Component Designer.
InitializeComponent()
End Sub
'Component overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Component Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Component Designer
'It can be modified using the Component Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
End Sub
' <snippet2>
#Region "IListSource Members"
' <snippet3>
Public ReadOnly Property ContainsListCollection() As Boolean Implements System.ComponentModel.IListSource.ContainsListCollection
Get
Return False
End Get
End Property
' </snippet3>
' <snippet4>
Public Function GetList() As System.Collections.IList Implements System.ComponentModel.IListSource.GetList
Dim ble As New BindingList(Of Employee)
If Not Me.DesignMode Then
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))
End If
Return ble
End Function
' </snippet4>
#End Region
' </snippet2>
End Class
' </snippet1>
@@ -0,0 +1,140 @@
' <snippet1000>
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Friend WithEvents flowLayoutPanel1 As FlowLayoutPanel
Friend WithEvents label2 As Label
Friend WithEvents dataGridView1 As DataGridView
Friend WithEvents nameDataGridViewTextBoxColumn As DataGridViewTextBoxColumn
Friend WithEvents salaryDataGridViewTextBoxColumn As DataGridViewTextBoxColumn
Friend WithEvents iDDataGridViewTextBoxColumn As DataGridViewTextBoxColumn
Friend WithEvents employeeListSource1 As EmployeeListSource
Public Sub New()
MyBase.New()
Me.InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
components = New System.ComponentModel.Container()
Dim dataGridViewCellStyle1 = New System.Windows.Forms.DataGridViewCellStyle()
Dim dataGridViewCellStyle2 = New System.Windows.Forms.DataGridViewCellStyle()
Me.flowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel()
Me.label2 = New System.Windows.Forms.Label()
Me.dataGridView1 = New System.Windows.Forms.DataGridView()
Me.nameDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.salaryDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.iDDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.employeeListSource1 = New EmployeeListSource(Me.components)
Me.flowLayoutPanel1.SuspendLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
' flowLayoutPanel1
'
Me.flowLayoutPanel1.AutoSize = True
Me.flowLayoutPanel1.Controls.Add(Me.label2)
Me.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top
Me.flowLayoutPanel1.Location = New System.Drawing.Point(0, 0)
Me.flowLayoutPanel1.Name = "flowLayoutPanel1"
Me.flowLayoutPanel1.Size = New System.Drawing.Size(416, 51)
Me.flowLayoutPanel1.TabIndex = 11
'
' label2
'
Me.label2.AutoSize = True
Me.label2.Location = New System.Drawing.Point(3, 6)
Me.label2.Margin = New System.Windows.Forms.Padding(3, 6, 3, 6)
Me.label2.Name = "label2"
Me.label2.Size = New System.Drawing.Size(408, 39)
Me.label2.TabIndex = 0
Me.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
'
Me.dataGridView1.AllowUserToAddRows = False
Me.dataGridView1.AllowUserToDeleteRows = False
dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192)
Me.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1
Me.dataGridView1.AutoGenerateColumns = False
Me.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dataGridView1.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() { _
Me.nameDataGridViewTextBoxColumn, Me.salaryDataGridViewTextBoxColumn, Me.iDDataGridViewTextBoxColumn})
Me.dataGridView1.DataSource = Me.employeeListSource1
Me.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill
Me.dataGridView1.Location = New System.Drawing.Point(0, 51)
Me.dataGridView1.Name = "dataGridView1"
Me.dataGridView1.RowHeadersVisible = False
Me.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
Me.dataGridView1.Size = New System.Drawing.Size(416, 215)
Me.dataGridView1.TabIndex = 12
'
' nameDataGridViewTextBoxColumn
'
Me.nameDataGridViewTextBoxColumn.DataPropertyName = "Name"
Me.nameDataGridViewTextBoxColumn.FillWeight = 131.7987F
Me.nameDataGridViewTextBoxColumn.HeaderText = "Name"
Me.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn"
'
' salaryDataGridViewTextBoxColumn
'
Me.salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID"
Me.salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2
Me.salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F
Me.salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID"
Me.salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn"
'
' iDDataGridViewTextBoxColumn
'
Me.iDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill
Me.iDDataGridViewTextBoxColumn.DataPropertyName = "ID"
Me.iDDataGridViewTextBoxColumn.FillWeight = 46.37391F
Me.iDDataGridViewTextBoxColumn.HeaderText = "ID"
Me.iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn"
Me.iDDataGridViewTextBoxColumn.ReadOnly = True
'
' Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(416, 266)
Me.Controls.Add(Me.dataGridView1)
Me.Controls.Add(Me.flowLayoutPanel1)
Me.Name = "Form1"
Me.Text = "IListSource Sample"
Me.flowLayoutPanel1.ResumeLayout(False)
Me.flowLayoutPanel1.PerformLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Shared Sub Main()
Application.Run(New Form1())
End Sub
End Class
' </snippet1000>
@@ -0,0 +1,5 @@
ITypedList.exe: BusinessObjectBase.vb Employee.vb EmployeeListSource.vb Form1.vb
vbc /t:exe /out:ITypedList.exe BusinessObjectBase.vb Employee.vb EmployeeListSource.vb Form1.vb
clean:
del *.dll *.bin *.exe
@@ -0,0 +1,139 @@
' <snippet1>
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms
' 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 Class Form1
Inherits System.Windows.Forms.Form
' This button causes the value of a list element to be changed.
Private changeItemBtn As New Button()
' This DataGridView control displays the contents of the list.
Private customersDataGridView As New DataGridView()
' This BindingSource binds the list to the DataGridView control.
Private customersBindingSource As New BindingSource()
Public Sub New()
InitializeComponent()
' Set up the "Change Item" button.
Me.changeItemBtn.Text = "Change Item"
Me.changeItemBtn.Dock = DockStyle.Bottom
AddHandler Me.changeItemBtn.Click, AddressOf changeItemBtn_Click
Me.Controls.Add(Me.changeItemBtn)
' Set up the DataGridView.
customersDataGridView.Dock = DockStyle.Top
Me.Controls.Add(customersDataGridView)
Me.Size = New Size(400, 200)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Create and populate the list of DemoCustomer objects
' which will supply data to the DataGridView.
Dim customerList As New BindingList(Of DemoCustomer)
customerList.Add(DemoCustomer.CreateNewCustomer())
customerList.Add(DemoCustomer.CreateNewCustomer())
customerList.Add(DemoCustomer.CreateNewCustomer())
' Bind the list to the BindingSource.
Me.customersBindingSource.DataSource = customerList
' Attach the BindingSource to the DataGridView.
Me.customersDataGridView.DataSource = Me.customersBindingSource
End Sub
' This event handler changes the value of the CompanyName
' property for the first item in the list.
Private Sub changeItemBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
' Get a reference to the list from the BindingSource.
Dim customerList As BindingList(Of DemoCustomer) = _
CType(customersBindingSource.DataSource, BindingList(Of 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"
End Sub
End Class
' <snippet9>
' This class implements a simple customer type
' that implements the IPropertyChange interface.
Public Class DemoCustomer
Implements INotifyPropertyChanged
' These fields hold the values for the public properties.
Private idValue As Guid = Guid.NewGuid()
Private customerNameValue As String = String.Empty
Private phoneNumberValue As String = String.Empty
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.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 Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
' The constructor is private to enforce the factory pattern.
Private Sub New()
customerNameValue = "Customer"
phoneNumberValue = "(312)555-0100"
End Sub
' This is the public factory method.
Public Shared Function CreateNewCustomer() As DemoCustomer
Return New DemoCustomer()
End Function
' This property represents an ID, suitable
' for use as a primary key in a database.
Public ReadOnly Property ID() As Guid
Get
Return Me.idValue
End Get
End Property
Public Property CustomerName() As String
Get
Return Me.customerNameValue
End Get
Set(ByVal value As String)
If Not (value = customerNameValue) Then
Me.customerNameValue = value
NotifyPropertyChanged()
End If
End Set
End Property
Public Property PhoneNumber() As String
Get
Return Me.phoneNumberValue
End Get
Set(ByVal value As String)
If Not (value = phoneNumberValue) Then
Me.phoneNumberValue = value
NotifyPropertyChanged()
End If
End Set
End Property
End Class
' </snippet9>
' </snippet1>
@@ -0,0 +1,138 @@
' <snippet10>
Imports System.ComponentModel
Public Class Customer
Implements INotifyPropertyChanged
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal company As String, ByVal address As String, ByVal city As String, ByVal state As String, ByVal zip As String)
Me._id = id
Me._name = name
Me._company = company
Me._address = address
Me._city = city
Me._state = state
Me._zip = zip
End Sub
#Region "Public Properties"
Private _id As Integer
Public Property ID() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
If _id <> value Then
_id = value
OnPropertyChanged(New PropertyChangedEventArgs("ID"))
End If
End Set
End Property
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
If _name <> value Then
_name = value
OnPropertyChanged(New PropertyChangedEventArgs("Name"))
End If
End Set
End Property
Private _company As String
Public Property Company() As String
Get
Return _company
End Get
Set(ByVal value As String)
If _company <> value Then
_company = value
OnPropertyChanged(New PropertyChangedEventArgs("Company"))
End If
End Set
End Property
Private _address As String
Public Property Address() As String
Get
Return _address
End Get
Set(ByVal value As String)
If _address <> value Then
_address = value
OnPropertyChanged(New PropertyChangedEventArgs("Address"))
End If
End Set
End Property
Private _city As String
Public Property City() As String
Get
Return _city
End Get
Set(ByVal value As String)
If _city <> value Then
_city = value
OnPropertyChanged(New PropertyChangedEventArgs("City"))
End If
End Set
End Property
Private _state As String
Public Property State() As String
Get
Return _state
End Get
Set(ByVal value As String)
If _state <> value Then
_state = value
OnPropertyChanged(New PropertyChangedEventArgs("State"))
End If
End Set
End Property
Private _zip As String
Public Property ZipCode() As String
Get
Return _zip
End Get
Set(ByVal value As String)
If _zip <> value Then
_zip = value
OnPropertyChanged(New PropertyChangedEventArgs("ZipCode"))
End If
End Set
End Property
#End Region
#Region "INotifyPropertyChanged Members"
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)
RaiseEvent PropertyChanged(Me, e)
End Sub
#End Region
End Class
' </snippet10>
@@ -0,0 +1,150 @@
' <snippet100>
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Friend WithEvents flowLayoutPanel1 As FlowLayoutPanel
Friend WithEvents label2 As System.Windows.Forms.Label
Friend WithEvents dataGridView1 As DataGridView
Friend WithEvents button1 As Button
Friend WithEvents button2 As Button
Dim sortableBindingListOfCustomers As SortableBindingList(Of Customer)
Dim bindingListOfCustomers As BindingList(Of Customer)
Public Sub New()
MyBase.New()
Me.InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sortableBindingListOfCustomers = New SortableBindingList(Of Customer)()
bindingListOfCustomers = New BindingList(Of Customer)()
Me.dataGridView1.DataSource = bindingListOfCustomers
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Me.dataGridView1.DataSource = Nothing
Me.dataGridView1.DataSource = sortableBindingListOfCustomers
End Sub
Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
Me.dataGridView1.DataSource = Nothing
Me.dataGridView1.DataSource = bindingListOfCustomers
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'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 Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
Me.flowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel
Me.label2 = New System.Windows.Forms.Label
Me.dataGridView1 = New System.Windows.Forms.DataGridView
Me.button1 = New System.Windows.Forms.Button
Me.button2 = New System.Windows.Forms.Button
Me.flowLayoutPanel1.SuspendLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'flowLayoutPanel1
'
Me.flowLayoutPanel1.AutoSize = True
Me.flowLayoutPanel1.Controls.Add(Me.label2)
Me.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top
Me.flowLayoutPanel1.Location = New System.Drawing.Point(0, 0)
Me.flowLayoutPanel1.Name = "flowLayoutPanel1"
Me.flowLayoutPanel1.Size = New System.Drawing.Size(566, 51)
Me.flowLayoutPanel1.TabIndex = 13
'
'label2
'
Me.label2.AutoSize = True
Me.label2.Location = New System.Drawing.Point(3, 6)
Me.label2.Margin = New System.Windows.Forms.Padding(3, 6, 3, 6)
Me.label2.Name = "label2"
Me.label2.Size = New System.Drawing.Size(558, 39)
Me.label2.TabIndex = 0
Me.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
'
Me.dataGridView1.AllowUserToAddRows = False
Me.dataGridView1.AllowUserToDeleteRows = False
Me.dataGridView1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill
Me.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dataGridView1.Location = New System.Drawing.Point(6, 57)
Me.dataGridView1.Name = "dataGridView1"
Me.dataGridView1.ReadOnly = True
Me.dataGridView1.RowHeadersVisible = False
Me.dataGridView1.Size = New System.Drawing.Size(465, 51)
Me.dataGridView1.TabIndex = 14
'
'button1
'
Me.button1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.button1.Location = New System.Drawing.Point(477, 57)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(82, 23)
Me.button1.TabIndex = 15
Me.button1.Text = "Sort Columns"
Me.button1.UseVisualStyleBackColor = True
'
'button2
'
Me.button2.Location = New System.Drawing.Point(477, 86)
Me.button2.Name = "button2"
Me.button2.Size = New System.Drawing.Size(82, 23)
Me.button2.TabIndex = 16
Me.button2.Text = "Reset"
Me.button2.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(566, 120)
Me.Controls.Add(Me.button2)
Me.Controls.Add(Me.button1)
Me.Controls.Add(Me.dataGridView1)
Me.Controls.Add(Me.flowLayoutPanel1)
Me.Name = "Form1"
Me.Text = "ITypedList Sample"
Me.flowLayoutPanel1.ResumeLayout(False)
Me.flowLayoutPanel1.PerformLayout()
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Shared Sub Main()
Application.Run(New Form1())
End Sub
End Class
' </snippet100>
@@ -0,0 +1,63 @@
' <snippet1>
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Windows.Forms
<Serializable()> _
Public Class SortableBindingList(Of Tkey)
Inherits BindingList(Of Tkey)
Implements ITypedList
<NonSerialized()> _
Private properties As PropertyDescriptorCollection
Public Sub New()
MyBase.New()
' Get the 'shape' of the list.
' Only get the public properties marked with Browsable = true.
Dim pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(Tkey), New Attribute() {New BrowsableAttribute(True)})
' Sort the properties.
properties = pdc.Sort()
End Sub
' <snippet2>
#Region "ITypedList Implementation"
' <snippet3>
Public Function GetItemProperties(ByVal listAccessors() As System.ComponentModel.PropertyDescriptor) As System.ComponentModel.PropertyDescriptorCollection Implements System.ComponentModel.ITypedList.GetItemProperties
Dim pdc As PropertyDescriptorCollection
If (Not (listAccessors Is Nothing)) And (listAccessors.Length > 0) Then
' Return child list shape
pdc = ListBindingHelper.GetListItemProperties(listAccessors(0).PropertyType)
Else
' Return properties in sort order
pdc = properties
End If
Return pdc
End Function
' </snippet3>
' <snippet4>
' This method is only used in the design-time framework
' and by the obsolete DataGrid control.
Public Function GetListName( _
ByVal listAccessors() As PropertyDescriptor) As String _
Implements System.ComponentModel.ITypedList.GetListName
Return GetType(Tkey).Name
End Function
' </snippet4>
#End Region
' </snippet2>
End Class
' </snippet1>
@@ -0,0 +1,5 @@
ITypedList.exe: SortableBindingList.vb Customer.vb Form1.vb
vbc /t:exe /out:ITypedList.exe SortableBindingList.vb Customer.vb Form1.vb
clean:
del *.dll *.bin *.exe
@@ -0,0 +1,143 @@
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Public Sub New()
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
Private Sub AlignTextWithTextRenderer(ByVal e As PaintEventArgs)
'<snippet20>
Dim text2 As String = "Use TextFormatFlags and Rectangle objects to" & _
" center text in a rectangle."
Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)
Try
Dim rect2 As New Rectangle(150, 10, 130, 140)
' Create a TextFormatFlags with word wrapping, horizontal center and
' vertical center specified.
Dim flags As TextFormatFlags = TextFormatFlags.HorizontalCenter Or _
TextFormatFlags.VerticalCenter Or 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)
Finally
font2.Dispose()
End Try
'</snippet20>
End Sub
Private Sub AlignTextWithDrawString(ByVal e As PaintEventArgs)
'<snippet10>
Dim text1 As String = "Use StringFormat and Rectangle objects to" & _
" center text in a rectangle."
Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)
Try
Dim rect1 As 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.
Dim stringFormat As 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)
Finally
font1.Dispose()
End Try
'</snippet10>
End Sub
Private Sub DrawTextAtLocation1(ByVal e As PaintEventArgs)
'<snippet30>
Dim font1 As New Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel)
Try
Dim pointF1 As New PointF(30, 10)
e.Graphics.DrawString("Hello", font1, Brushes.Blue, pointF1)
Finally
font1.Dispose()
End Try
'</snippet30>
End Sub
Private Sub DrawTextAtLocation2(ByVal e As PaintEventArgs)
'<snippet40>
Dim font As New Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel)
Try
Dim point1 As New Point(30, 10)
TextRenderer.DrawText(e.Graphics, "Hello", font, point1, Color.Blue)
Finally
font.Dispose()
End Try
'</snippet40>
End Sub
Private Sub DrawTextInARectangle1(ByVal e As PaintEventArgs)
'<snippet50>
Dim text1 As String = "Draw text in a rectangle by passing a RectF to the DrawString method."
Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)
Try
Dim rectF1 As New RectangleF(30, 10, 100, 122)
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1)
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1))
Finally
font1.Dispose()
End Try
'</snippet50>
End Sub
Private Sub DrawTextInARectangle2(ByVal e As PaintEventArgs)
'<snippet60>
Dim text2 As String = _
"Draw text in a rectangle by passing a RectF to the DrawString method."
Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)
Try
Dim rect2 As New Rectangle(30, 10, 100, 122)
' Specify the text is wrapped.
Dim flags As TextFormatFlags = TextFormatFlags.WordBreak
TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags)
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2))
Finally
font2.Dispose()
End Try
'</snippet60>
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
Handles Me.Paint
'AlignTextWithDrawString(e);
'AlignTextWithTextRenderer(e);
'DrawTextAtLocation1(e);
'DrawTextAtLocation2(e);
DrawTextInARectangle1(e)
End Sub
End Class
@@ -0,0 +1,167 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Public Class SystemDrawingAlphaBlending
' 8f2508af-f495-4223-b5cc-646cbbb520eb
' How to: Draw Opaque and Semitransparent Lines
Public Sub Method11(ByVal e As PaintEventArgs)
' <snippet11>
Dim bitmap As New Bitmap("Texture1.jpg")
e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height)
Dim opaquePen As New Pen(Color.FromArgb(255, 0, 0, 255), 15)
Dim semiTransPen As 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>
End Sub
' a27121e6-f7e9-4c09-84e2-f05aa9d2a1bb
' How to: Use a Color Matrix to Set Alpha Values in Images
Public Sub Method21(ByVal e As PaintEventArgs)
' <snippet21>
' Create the Bitmap object and load it with the texture image.
Dim bitmap As New Bitmap("Texture.jpg")
' Initialize the color matrix.
' Note the value 0.8 in row 4, column 4.
Dim matrixItems As Single()() = { _
New Single() {1, 0, 0, 0, 0}, _
New Single() {0, 1, 0, 0, 0}, _
New Single() {0, 0, 1, 0, 0}, _
New Single() {0, 0, 0, 0.8F, 0}, _
New Single() {0, 0, 0, 0, 1}}
Dim colorMatrix As New ColorMatrix(matrixItems)
' Create an ImageAttributes object and set its color matrix.
Dim imageAtt As 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.
Dim iWidth As Integer = bitmap.Width
Dim iHeight As Integer = bitmap.Height
' Pass in the destination rectangle (2nd argument) and the x _
' coordinate (3rd argument), x coordinate (4th argument), width _
' (5th argument), and height (6th argument) of the source rectangle.
e.Graphics.DrawImage( _
bitmap, _
New Rectangle(30, 0, iWidth, iHeight), _
0.0F, _
0.0F, _
iWidth, _
iHeight, _
GraphicsUnit.Pixel, _
imageAtt)
' </snippet21>
End Sub
' a4f6f6b8-3bc8-440a-84af-d62ef0f8ff40
' How to: Draw with Opaque and Semitransparent Brushes
Public Sub Method31(ByVal e As PaintEventArgs)
' <snippet31>
Dim bitmap As New Bitmap("Texture1.jpg")
e.Graphics.DrawImage(bitmap, 50, 50, bitmap.Width, bitmap.Height)
Dim opaqueBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
Dim semiTransBrush As 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>
End Sub
' f331df2d-b395-4b0a-95be-24fec8c9bbb5
' How to: Use Compositing Mode to Control Alpha Blending
Public Sub Method41()
' Create a blank bitmap.
Dim myBitmap As New Bitmap(180, 100)
' Create a Graphics object that we can use to draw on the bitmap.
Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap)
' <snippet41>
bitmapGraphics.CompositingMode = CompositingMode.SourceCopy
' </snippet41>
End Sub
Public Sub Method42()
' Create a blank bitmap.
Dim myBitmap As New Bitmap(180, 100)
' Create a Graphics object that we can use to draw on the bitmap.
Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap)
' <snippet42>
bitmapGraphics.CompositingMode = CompositingMode.SourceOver
' </snippet42>
End Sub
Public Sub Method43(ByVal e As PaintEventArgs)
' <snippet43>
' Create a blank bitmap.
Dim myBitmap As New Bitmap(180, 100)
' Create a Graphics object that we can use to draw on the bitmap.
Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap)
' Create a red brush and a green brush, each with an alpha value of 160.
Dim redBrush As New SolidBrush(Color.FromArgb(160, 255, 0, 0))
Dim greenBrush As 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.
Dim colorBrush As 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>
End Sub
End Class
@@ -0,0 +1,143 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub DoSomething1()
' Snippet for: \vbtskcodeexampledrawingfilledellipseonform.xml
' <snippet1>
Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.FillEllipse(myBrush, New Rectangle(0, 0, 200, 300))
myBrush.Dispose()
formGraphics.Dispose()
' </snippet1>
End Sub
Private Sub DoSomething2()
' Snippet for: \vbtskcodeexampledrawingfilledrectangleonform.xml
' <snippet2>
Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.FillRectangle(myBrush, New Rectangle(0, 0, 200, 300))
myBrush.Dispose()
formGraphics.Dispose()
' </snippet2>
End Sub
Private Sub DoSomething3()
' Snippet for: \vbtskcodeexamplecreatingpen.xml
' <snippet3>
Dim myPen As System.Drawing.Pen
myPen = New System.Drawing.Pen(System.Drawing.Color.Tomato)
' </snippet3>
End Sub
Private Sub DoSomething4()
' Snippet for: \vbtskcodeexamplecreatingsolidbrush.xml
' <snippet4>
Dim myBrush As System.Drawing.SolidBrush
myBrush = New System.Drawing.SolidBrush(System.Drawing.Color.PeachPuff)
' </snippet4>
End Sub
Private Sub DoSomething5()
' Snippet for: \vbtskcodeexampledrawinglineonform.xml
' <snippet5>
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawLine(myPen, 0, 0, 200, 200)
myPen.Dispose()
formGraphics.Dispose()
' </snippet5>
End Sub
' Snippet for: \vbtskcodeexampledrawingoutlinedshapes.xml
' <snippet6>
Private Sub DrawEllipse()
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawEllipse(myPen, New Rectangle(0, 0, 200, 300))
myPen.Dispose()
formGraphics.Dispose()
End Sub
Private Sub DrawRectangle()
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawRectangle(myPen, New Rectangle(0, 0, 200, 300))
myPen.Dispose()
formGraphics.Dispose()
End Sub
' </snippet6>
' Snippet for: \vbtskcodeexampledrawingtextonform2.xml
' <snippet7>
Public Sub DrawString()
Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
Dim drawString As String = "Sample Text"
Dim drawFont As New System.Drawing.Font("Arial", 16)
Dim drawBrush As New _
System.Drawing.SolidBrush(System.Drawing.Color.Black)
Dim x As Single = 150.0
Dim y As Single = 50.0
Dim drawFormat As New System.Drawing.StringFormat
formGraphics.DrawString(drawString, drawFont, drawBrush, _
x, y, drawFormat)
drawFont.Dispose()
drawBrush.Dispose()
formGraphics.Dispose()
End Sub
' </snippet7>
' Snippet for: \vbtskcodeexampledrawingtextonform.xml
' <snippet8>
Public Sub DrawVerticalString()
Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
Dim drawString As String = "Sample Text"
Dim drawFont As New System.Drawing.Font("Arial", 16)
Dim drawBrush As New _
System.Drawing.SolidBrush(System.Drawing.Color.Black)
Dim x As Single = 150.0
Dim y As Single = 50.0
Dim drawFormat As New System.Drawing.StringFormat
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical
formGraphics.DrawString(drawString, drawFont, drawBrush, _
x, y, drawFormat)
drawFont.Dispose()
drawBrush.Dispose()
formGraphics.Dispose()
End Sub
' </snippet8>
Private Sub DoSomething9()
Dim myPen As New Pen(Color.Red)
' Snippet for: \vbtskcodeexamplesetcolorofpen.xml
' <snippet9>
myPen.Color = System.Drawing.Color.PeachPuff
' </snippet9>
End Sub
' Snippet for: \vbtskcreateashapedwindowsform.xml
' <snippet10>
Protected Overrides Sub OnPaint( _
ByVal e As System.Windows.Forms.PaintEventArgs)
Dim shape As New System.Drawing.Drawing2D.GraphicsPath
shape.AddEllipse(0, 0, Me.Width, Me.Height)
Me.Region = New System.Drawing.Region(shape)
End Sub
' </snippet10>
<STAThread()> Public Shared Sub Main()
Application.Run(New Form1)
End Sub
End Class
@@ -0,0 +1,102 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Drawing2D
Public Class SystemDrawingConstructingDrawingCurves
' 37a0bedb-20c2-4cf0-91fa-a5509e826b30
' How to: Draw a Sequence of Bézier Splines
Private Sub Method11(ByVal e As PaintEventArgs)
' <snippet11>
' Point(10, 100) = start point of first spline
' Point(75, 10) = first control point of first spline
' Point(80, 50) = second control point of first spline
' Point(100, 150) = endpoint of first spline and start point of second spline
' Point(125, 80) = first control point of second spline
' Point(175, 200) = second control point of second spline
' Point(200, 80)} = endpoint of second spline
Dim p As Point() = { _
New Point(10, 100), _
New Point(75, 10), _
New Point(80, 50), _
New Point(100, 150), _
New Point(125, 80), _
New Point(175, 200), _
New Point(200, 80)}
Dim pen As New Pen(Color.Blue)
e.Graphics.DrawBeziers(pen, p)
' </snippet11>
End Sub
' a4a41e80-4461-4b47-b6bd-2c5e68881994
' How to: Draw Cardinal Splines
Private Sub Method21(ByVal e As PaintEventArgs)
' <snippet21>
Dim points As Point() = { _
New Point(0, 100), _
New Point(50, 80), _
New Point(100, 20), _
New Point(150, 80), _
New Point(200, 100)}
Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255))
e.Graphics.DrawCurve(pen, points)
' </snippet21>
End Sub
Private Sub Method22(ByVal e As PaintEventArgs)
' <snippet22>
Dim points As Point() = { _
New Point(60, 60), _
New Point(150, 80), _
New Point(200, 40), _
New Point(180, 120), _
New Point(120, 100), _
New Point(80, 160)}
Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255))
e.Graphics.DrawClosedCurve(pen, points)
' </snippet22>
End Sub
Private Sub Method23(ByVal e As PaintEventArgs)
' <snippet23>
Dim points As Point() = { _
New Point(20, 50), _
New Point(100, 10), _
New Point(200, 100), _
New Point(300, 50), _
New Point(400, 80)}
Dim pen As 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>
End Sub
' f4f3fe30-f0a6-4743-ac91-11310cebea9f
' How to: Draw a Single Bézier Spline
Private Sub Method31(ByVal e As PaintEventArgs)
' <snippet31>
Dim p1 As New Point(10, 100) ' Start point
Dim c1 As New Point(100, 10) ' First control point
Dim c2 As New Point(150, 150) ' Second control point
Dim p2 As New Point(200, 100) ' Endpoint
Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255))
e.Graphics.DrawBezier(pen, p1, c1, c2, p2)
' </snippet31>
End Sub
End Class
@@ -0,0 +1,68 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Drawing2D
Public Class SystemDrawingConstructingDrawingPaths
' 5a36b0e4-f1f4-46c0-a85a-22ae98491950
' How to: Fill Open Figures
Private Sub Method11(ByVal e As PaintEventArgs)
' <snippet11>
Dim path As 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)
Dim pen As New Pen(Color.FromArgb(128, 0, 0, 255), 5)
Dim brush As New SolidBrush(Color.Red)
' The fill mode is FillMode.Alternate by default.
e.Graphics.FillPath(brush, path)
e.Graphics.DrawPath(pen, path)
' </snippet11>
End Sub
' 82fd56c7-b443-4765-9b7c-62ce030656ec
' How to: Create Figures from Lines, Curves, and Shapes
Private Sub Method21(ByVal e As PaintEventArgs)
' <snippet21>
Dim path As New GraphicsPath()
path.AddArc(175, 50, 50, 50, 0, -180)
e.Graphics.DrawPath(New Pen(Color.FromArgb(128, 255, 0, 0), 4), path)
' </snippet21>
End Sub
Private Sub Method22(ByVal e As PaintEventArgs)
' <snippet22>
' Create an array of points for the curve in the second figure.
Dim points As Point() = { _
New Point(40, 60), _
New Point(50, 70), _
New Point(30, 90)}
Dim path As 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>
End Sub
End Class
@@ -0,0 +1,128 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Public Class Form1
Inherits Form
<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
Dim myPen As Pen = Pens.Black
' 0659fe00-9e0c-41c4-9118-016f2404c905
' Matrix Representation of Transformations
Public Sub Method11()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet11>
Dim myMatrix As New Matrix()
myMatrix.Rotate(30)
myMatrix.Scale(1, 2, MatrixOrder.Append)
myMatrix.Translate(5, 0, MatrixOrder.Append)
' </snippet11>
End Sub
' b601d66d-d572-4f11-9d2e-92f0dc8893f3
' Global and Local Transformations
Public Sub Method21()
Dim myGraphics As Graphics = Me.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>
End Sub
Public Sub Method22()
Dim myGraphics As Graphics = Me.CreateGraphics()
Dim myGraphicsPath As New GraphicsPath()
' <snippet22>
Dim myMatrix As New Matrix()
myMatrix.Rotate(45)
myGraphicsPath.Transform(myMatrix)
myGraphics.DrawRectangle(myPen, 10, 10, 100, 50)
myGraphics.DrawPath(myPen, myGraphicsPath)
' </snippet22>
End Sub
Public Sub Method23()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet23>
Dim myMatrix As New Matrix(1, 0, 0, -1, 0, 0)
myGraphics.Transform = myMatrix
myGraphics.TranslateTransform(200, 150, MatrixOrder.Append)
' </snippet23>
End Sub
Public Sub Method24()
Dim myGraphics As Graphics = Me.CreateGraphics()
Dim mySolidBrush1 As New SolidBrush(Color.Red)
Dim mySolidBrush2 As New SolidBrush(Color.Black)
' <snippet24>
' Create the path.
Dim myGraphicsPath As New GraphicsPath()
Dim myRectangle As 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.
Dim myPathMatrix As 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>
End Sub
' c61ff50a-eb1d-4e6c-83cd-f7e9764cfa9f
' Types of Coordinate Systems
Public Sub Method31()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet31>
myGraphics.TranslateTransform(100, 50)
myGraphics.DrawLine(myPen, 0, 0, 160, 80)
' </snippet31>
End Sub
Public Sub Method32()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet32>
myGraphics.PageUnit = GraphicsUnit.Inch
myGraphics.DrawLine(myPen, 0, 0, 2, 1)
' </snippet32>
End Sub
Public Sub Method33()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet33>
Dim myPen As New Pen(Color.Black, 1 / myGraphics.DpiX)
' </snippet33>
End Sub
Public Sub Method34()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet34>
myGraphics.TranslateTransform(2, 0.5F)
myGraphics.PageUnit = GraphicsUnit.Inch
myGraphics.DrawLine(myPen, 0, 0, 2, 1)
' </snippet34>
End Sub
End Class
@@ -0,0 +1,54 @@
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Public Sub New()
CreateBitmapAtRuntime()
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
'<snippet1>
Private pictureBox1 As New PictureBox()
Public Sub CreateBitmapAtRuntime()
pictureBox1.Size = New Size(210, 110)
Me.Controls.Add(pictureBox1)
Dim flag As New Bitmap(200, 100)
Dim flagGraphics As Graphics = Graphics.FromImage(flag)
Dim red As Integer = 0
Dim white As Integer = 11
While white <= 100
flagGraphics.FillRectangle(Brushes.Red, 0, red, 200, 10)
flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10)
red += 20
white += 20
End While
pictureBox1.Image = flag
End Sub
'</snippet1>
End Class
@@ -0,0 +1,392 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Text
Public Class SystemDrawingFontsAndText
' 26d74ef5-0f39-4eeb-8d20-00e66e014abe
' How to: Enumerate Installed Fonts
Public Sub Method11(ByVal e As PaintEventArgs)
' <snippet11>
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
fontFamily, _
8, _
FontStyle.Regular, _
GraphicsUnit.Point)
Dim rectF As New RectangleF(10, 10, 500, 500)
Dim solidBrush As New SolidBrush(Color.Black)
Dim familyName As String
Dim familyList As String = ""
Dim fontFamilies() As FontFamily
Dim installedFontCollection As 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.
Dim count As Integer = fontFamilies.Length
Dim j As Integer
While j < count
familyName = fontFamilies(j).Name
familyList = familyList & familyName
familyList = familyList & ", "
j += 1
End While
' Draw the large string (list of all families) in a rectangle.
e.Graphics.DrawString(familyList, font, solidBrush, rectF)
' </snippet11>
End Sub
' 48fc34f3-f236-4b01-a0cb-f0752e6d22ae
' How to: Use Antialiasing with Text
Public Sub Method21(ByVal e As PaintEventArgs)
' <snippet21>
Dim fontFamily As New FontFamily("Times New Roman")
Dim font As New Font( _
fontFamily, _
32, _
FontStyle.Regular, _
GraphicsUnit.Pixel)
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
Dim string1 As String = "SingleBitPerPixel"
Dim string2 As String = "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>
End Sub
' 50c69046-4188-47d9-b949-cc2610ffd337
' How to: Create Vertical Text
Public Sub Method31(ByVal e As PaintEventArgs)
' <snippet31>
Dim myText As String = "Vertical text"
Dim fontFamily As New FontFamily("Lucida Console")
Dim font As New Font( _
fontFamily, _
14, _
FontStyle.Regular, _
GraphicsUnit.Point)
Dim pointF As New PointF(40, 10)
Dim stringFormat As New StringFormat()
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
stringFormat.FormatFlags = StringFormatFlags.DirectionVertical
e.Graphics.DrawString(myText, font, solidBrush, pointF, stringFormat)
' </snippet31>
End Sub
' 64878f98-39ba-4303-b63f-0859ab682eeb
' How to: Set Tab Stops in Drawn Text
Public Sub Method41(ByVal e As PaintEventArgs)
' <snippet41>
Dim myText As String = _
"Name" & ControlChars.Tab & _
"Test 1" & ControlChars.Tab & _
"Test 2" & ControlChars.Tab & _
"Test 3" & ControlChars.Cr
myText = myText & "Joe" & ControlChars.Tab & _
"95" & ControlChars.Tab & _
"88" & ControlChars.Tab & _
"91" & ControlChars.Cr
myText = myText & "Mary" & ControlChars.Tab & _
"98" & ControlChars.Tab & _
"84" & ControlChars.Tab & _
"90" & ControlChars.Cr
myText = myText & "Sam" & ControlChars.Tab & _
"42" & ControlChars.Tab & _
"76" & ControlChars.Tab & _
"98" & ControlChars.Cr
myText = myText & "Jane" & ControlChars.Tab & _
"65" & ControlChars.Tab & _
"73" & ControlChars.Tab & _
"92" & ControlChars.Cr
Dim fontFamily As New FontFamily("Courier New")
Dim font As New Font( _
fontFamily, _
12, _
FontStyle.Regular, _
GraphicsUnit.Point)
Dim rect As New Rectangle(10, 10, 450, 100)
Dim stringFormat As New StringFormat()
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255))
Dim tabs As Single() = {150, 100, 100, 100}
stringFormat.SetTabStops(0, tabs)
e.Graphics.DrawString(myText, font, solidBrush, RectangleF.op_implicit(rect), stringFormat)
Dim pen As Pen = Pens.Black
e.Graphics.DrawRectangle(pen, rect)
' </snippet41>
End Sub
' 6533d5e5-a8dc-4b76-9fc4-3bf75c8b9212
' How to: Create a Private Font Collection
Public Sub Method51(ByVal e As PaintEventArgs)
' <snippet51>
Dim pointF As New PointF(10, 0)
Dim solidBrush As New SolidBrush(Color.Black)
Dim count As Integer = 0
Dim familyName As String = ""
Dim familyNameAndStyle As String
Dim fontFamilies() As FontFamily
Dim privateFontCollection As 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.
Dim j As Integer
While j < count
' Get the font family name.
familyName = fontFamilies(j).Name
' Is the regular style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Regular) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & " Regular"
Dim regFont As New Font( _
familyName, _
16, _
FontStyle.Regular, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
regFont, _
solidBrush, _
pointF)
pointF.Y += regFont.Height
End If
' Is the bold style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & " Bold"
Dim boldFont As New Font( _
familyName, _
16, _
FontStyle.Bold, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
boldFont, _
solidBrush, _
pointF)
pointF.Y += boldFont.Height
End If
' Is the italic style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & " Italic"
Dim italicFont As New Font( _
familyName, _
16, _
FontStyle.Italic, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
italicFont, _
solidBrush, pointF)
pointF.Y += italicFont.Height
End If
' Is the bold italic style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) And _
fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & "BoldItalic"
Dim italicFont As New Font( _
familyName, _
16, _
FontStyle.Italic Or FontStyle.Bold, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
italicFont, _
solidBrush, _
pointF)
pointF.Y += italicFont.Height
End If
' Is the underline style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Underline) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & " Underline"
Dim underlineFont As New Font( _
familyName, _
16, _
FontStyle.Underline, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
underlineFont, _
solidBrush, _
pointF)
pointF.Y += underlineFont.Height
End If
' Is the strikeout style available?
If fontFamilies(j).IsStyleAvailable(FontStyle.Strikeout) Then
familyNameAndStyle = ""
familyNameAndStyle = familyNameAndStyle & familyName
familyNameAndStyle = familyNameAndStyle & " Strikeout"
Dim strikeFont As New Font( _
familyName, _
16, _
FontStyle.Strikeout, _
GraphicsUnit.Pixel)
e.Graphics.DrawString( _
familyNameAndStyle, _
strikeFont, _
solidBrush, _
pointF)
pointF.Y += strikeFont.Height
End If
' Separate the families with white space.
pointF.Y += 10
End While
' </snippet51>
End Sub
' d3a4a223-9492-4b54-9afd-db1c31c3cefd
' How to: Construct Font Families and Fonts
Public Sub Method61(ByVal e As PaintEventArgs)
' <snippet61>
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
fontFamily, _
16, _
FontStyle.Regular, _
GraphicsUnit.Pixel)
' </snippet61>
End Sub
' ff7c0616-67f7-4fa2-84ee-b8d642f2b09b
' How to: Obtain Font Metrics
Public Sub Method71(ByVal e As PaintEventArgs)
' <snippet71>
Dim infoString As String = "" ' enough space for one line of output
Dim ascent As Integer ' font family ascent in design units
Dim ascentPixel As Single ' ascent converted to pixels
Dim descent As Integer ' font family descent in design units
Dim descentPixel As Single ' descent converted to pixels
Dim lineSpacing As Integer ' font family line spacing in design units
Dim lineSpacingPixel As Single ' line spacing converted to pixels
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
fontFamily, _
16, _
FontStyle.Regular, _
GraphicsUnit.Pixel)
Dim pointF As New PointF(10, 10)
Dim solidBrush As New SolidBrush(Color.Black)
' Display the font size in pixels.
infoString = "font.Size returns " & font.Size.ToString() & "."
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>
End Sub
End Class
@@ -0,0 +1,42 @@
'<snippet1>
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Printing
Public Class Form1
Inherits Form
Private WithEvents printButton As New Button
Private WithEvents printDocument1 As New PrintDocument
Public Sub New()
printButton.Text = "Print Form"
Me.Controls.Add(printButton)
End Sub
Dim memoryImage As Bitmap
Private Sub CaptureScreen()
Dim myGraphics As Graphics = Me.CreateGraphics()
Dim s As Size = Me.Size
memoryImage = New Bitmap(s.Width, s.Height, myGraphics)
Dim memoryGraphics As Graphics = Graphics.FromImage(memoryImage)
memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As System.Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _
printDocument1.PrintPage
e.Graphics.DrawImage(memoryImage, 0, 0)
End Sub
Private Sub printButton_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles printButton.Click
CaptureScreen()
printDocument1.Print()
End Sub
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
End Class
'</snippet1>
@@ -0,0 +1,65 @@
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.IO
Public Class Form1
Inherits Form
Public Sub New()
ExtractAssociatedIconEx()
End Sub
' <snippet1>
Private listView1 As ListView
Private imageList1 As ImageList
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo("c:\")
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As System.IO.FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = 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 Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub
' </snippet1>
End Class
@@ -0,0 +1,118 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Imaging
Public Class Form1
Inherits Form
<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
' 09f0c07a-19c0-43b4-90a2-862a10545ce8
' Drawing, Positioning, and Cloning Images in GDI+
Public Sub Method11()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet11>
Dim myBitmap As New Bitmap("Climber.jpg")
myGraphics.DrawImage(myBitmap, 10, 10)
' </snippet11>
End Sub
Public Sub Method12()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet12>
Dim myBMP As New Bitmap("SpaceCadet.bmp")
Dim myGIF As New Bitmap("Soda.gif")
Dim myJPEG As New Bitmap("Mango.jpg")
Dim myPNG As New Bitmap("Flowers.png")
Dim myTIFF As 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>
End Sub
Public Sub Method13()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet13>
Dim originalBitmap As New Bitmap("Spiral.png")
Dim sourceRectangle As New Rectangle(0, 0, originalBitmap.Width, _
CType(originalBitmap.Height / 2, Integer))
Dim secondBitmap As Bitmap = originalBitmap.Clone(sourceRectangle, _
PixelFormat.DontCare)
myGraphics.DrawImage(originalBitmap, 10, 10)
myGraphics.DrawImage(secondBitmap, 150, 10)
' </snippet13>
End Sub
' 51da872c-c783-440f-8bf6-1e580a966c31
' Metafiles in GDI+
' <snippet21>
Public Sub Example_DisplayMetafile(ByVal e As PaintEventArgs)
Dim myGraphics As Graphics = e.Graphics
Dim myMetafile As New Metafile("SampleMetafile.emf")
myGraphics.DrawImage(myMetafile, 100, 100)
End Sub
' </snippet21>
' ad5daf26-005f-45bc-a2af-e0e97777a21a
' Cropping and Scaling Images in GDI+
Public Sub Method31()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet31>
Dim myBitmap As New Bitmap("Spiral.png")
Dim expansionRectangle As New Rectangle(135, 10, _
myBitmap.Width, myBitmap.Height)
Dim compressionRectangle As New Rectangle(300, 10, _
CType(myBitmap.Width / 2, Integer), CType(myBitmap.Height / 2, Integer))
myGraphics.DrawImage(myBitmap, 10, 10)
myGraphics.DrawImage(myBitmap, expansionRectangle)
myGraphics.DrawImage(myBitmap, compressionRectangle)
' </snippet31>
End Sub
Public Sub Method32()
Dim myGraphics As Graphics = Me.CreateGraphics()
' <snippet32>
Dim myBitmap As New Bitmap("Runner.jpg")
' One hand of the runner
Dim sourceRectangle As New Rectangle(80, 70, 80, 45)
' Compressed hand
Dim destRectangle1 As New Rectangle(200, 10, 20, 16)
' Expanded hand
Dim destRectangle2 As 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>
End Sub
End Class
@@ -0,0 +1,288 @@
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.ComponentModel
Imports System.Drawing.Text
Public Class Form1
Inherits System.Windows.Forms.Form
Public Sub New()
'This call is required by the Windows Form Designer.
InitializeComponent()
ExtractAssociatedIconEx()
End Sub
'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 Sub InitializeComponent()
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
<System.STAThread()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
'<snippet1>
Protected Sub DrawCaps(ByVal e As PaintEventArgs)
Dim hPath As 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.
Dim HookCap As New CustomLineCap(Nothing, 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.
Dim customCapPen As 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.
Dim capPen As New Pen(Color.Red, 10)
Dim startCap As LineCap
Dim endCap As LineCap
HookCap.GetStrokeCaps(startCap, endCap)
capPen.StartCap = startCap
capPen.EndCap = endCap
' Create a line to draw.
Dim points As Point() = {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)
End Sub
'</snippet1>
'<snippet2>
Private Sub ExtractAssociatedIconEx()
Dim ico As Icon = Icon.ExtractAssociatedIcon("C:\WINDOWS\system32\notepad.exe")
Me.Icon = ico
End Sub
'</snippet2>
'<snippet3>
Private Sub ConstructAnIconFromAType(ByVal e As PaintEventArgs)
Dim icon1 As New Icon(GetType(Control), "Error.ico")
e.Graphics.DrawIcon(icon1, New Rectangle(10, 10, 50, 50))
End Sub
'</snippet3>
' <snippet4>
Private Sub ShowOutputChannels(ByVal e As PaintEventArgs)
'Create a bitmap from a file.
Dim bmp1 As New Bitmap("c:\fakePhoto.jpg")
' Create a new bitmap from the original, resizing it for this example.
Dim bmp2 As New Bitmap(bmp1, New Size(80, 80))
bmp1.Dispose()
' Create an ImageAttributes object.
Dim imgAttributes As New System.Drawing.Imaging.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, 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, _
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()
End Sub
' </snippet4>
'<snippet5>
Private Sub OpAdditionExample(ByVal e As PaintEventArgs)
Dim size1 As New SizeF(120.5F, 30.5F)
Dim point1 As New PointF(20.5F, 20F)
Dim rect1 As New RectangleF(point1, size1)
If New PointF(rect1.Right, rect1.Bottom) = point1 + size1 Then
e.Graphics.DrawString("They are equal", Me.Font, Brushes.Black, rect1)
Else
e.Graphics.DrawString("They are not equal", Me.Font, Brushes.Red, rect1)
End If
End Sub
'</snippet5>
'<snippet6>
Private Sub AddExample(ByVal e As PaintEventArgs)
Dim size1 As New SizeF(120.5F, 30.5F)
Dim point1 As New PointF(20.5F, 20F)
Dim rect1 As New RectangleF(point1, size1)
Dim point2 As New PointF(rect1.Right, rect1.Bottom)
If point2 <> PointF.Add(point1, size1) Then
e.Graphics.DrawString("They are not equal", Me.Font, Brushes.Red, rect1)
Else
e.Graphics.DrawString("They are equal", Me.Font, Brushes.Black, rect1)
End If
End Sub
'</snippet6>
'<snippet7>
Private Sub SubtractExample(ByVal e As PaintEventArgs)
Dim point1 As New PointF(120.5F, 120F)
Dim size1 As New SizeF(120.5F, 30.5F)
Dim point2 As PointF = PointF.Subtract(point1, size1)
e.Graphics.DrawLine(Pens.Blue, point1, point2)
End Sub
'</snippet7>
'<snippet8>
Private Sub OpSubtractionExample(ByVal e As PaintEventArgs)
Dim point1 As New PointF(120.5F, 120F)
Dim size1 As New SizeF(120.5F, 30.5F)
Dim point2 As PointF = point1 - size1
e.Graphics.DrawLine(Pens.Blue, point1, point2)
End Sub
'</snippet8>
Private Sub ShearColors(ByVal e As PaintEventArgs)
'<snippet9>
Dim image = New Bitmap("ColorBars.bmp")
Dim imageAttributes As New ImageAttributes()
Dim width As Integer = image.Width
Dim height As Integer = image.Height
Dim colorMatrixElements As Single()() = _
{New Single() {1, 0, 0, 0, 0}, _
New Single() {0, 1, 0, 0, 0}, _
New Single() {0.5F, 0, 1, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}}
Dim colorMatrix As 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), 0, 0, _
width, height, GraphicsUnit.Pixel, imageAttributes)
'</snippet9>
End Sub
'<snippetInstalledFonts>
Private ifc As New InstalledFontCollection()
Private Sub EnumerateInstalledFonts(ByVal e As PaintEventArgs)
Dim families As FontFamily() = ifc.Families
Dim x As Single = 0.0F
Dim y As Single = 0.0F
For i As Integer = 0 To ifc.Families.Length - 1
If ifc.Families(i).IsStyleAvailable(FontStyle.Regular) Then
e.Graphics.DrawString(ifc.Families(i).Name, New Font(ifc.Families(i), 12), _
Brushes.Black, x, y)
y += 20
If y Mod 700 = 0 Then
x += 140
y = 0
End If
End If
Next
End Sub
'</snippetInstalledFonts>
'<snippetConstructFontWithString>
Private Sub ConstructFontWithString(ByVal e As PaintEventArgs)
Dim font1 As New Font("Arial", 20)
e.Graphics.DrawString("Arial Font", font1, Brushes.Red, New PointF(10, 10))
End Sub
'</snippetConstructFontWithString>
Private Shared Function ResizeImage(ByVal image As System.Drawing.Image) As Bitmap
'<snippetSetResolution>
Dim bitmap As New Bitmap(100, 100)
bitmap.SetResolution(96F, 96F)
'</snippetSetResolution>
Using graphics__1 As Graphics = Graphics.FromImage(bitmap)
graphics__1.DrawImage(image, New Rectangle(0, 0, 100, 100), New Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel)
End Using
Return bitmap
End Function
'<snippetGetThumbnail>
Public Function ThumbnailCallback() As Boolean
Return False
End Function
Public Sub Example_GetThumb(ByVal e As PaintEventArgs)
Dim myCallback As New Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
Dim myBitmap As New Bitmap("Climber.jpg")
Dim myThumbnail As Image = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero)
e.Graphics.DrawImage(myThumbnail, 150, 75)
End Sub
'</snippetGetThumbnail>
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
DrawCaps(e)
'ConstructAnIconFromAType(e);
ShowOutputChannels(e)
End Sub
End Class
@@ -0,0 +1,258 @@
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Xml
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Public Class SystemDrawingMiscLegacyTopics
' 1e717711-1361-448e-aa49-0f3ec43110c9
' Using the World Transformation
Private Sub Method11(ByVal e As PaintEventArgs)
' <snippet11>
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2)
e.Graphics.DrawRectangle(pen, rect)
' </snippet11>
End Sub
Private Sub Method12(ByVal e As PaintEventArgs)
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2)
' <snippet12>
e.Graphics.ScaleTransform(1.75F, 0.5F)
e.Graphics.DrawRectangle(pen, rect)
' </snippet12>
End Sub
Private Sub Method13(ByVal e As PaintEventArgs)
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2)
' <snippet13>
e.Graphics.ResetTransform()
e.Graphics.RotateTransform(28) ' 28 degrees
e.Graphics.DrawRectangle(pen, rect)
' </snippet13>
End Sub
Private Sub Method14(ByVal e As PaintEventArgs)
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2)
' <snippet14>
e.Graphics.ResetTransform()
e.Graphics.TranslateTransform(150, 150)
e.Graphics.DrawRectangle(pen, rect)
' </snippet14>
End Sub
' 37d5f9dc-a5cf-4475-aa5d-34d714e808a9
' Why Transformation Order Is Significant
Private Sub Method21(ByVal e As PaintEventArgs)
' <snippet21>
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As 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>
End Sub
Private Sub Method22(ByVal e As PaintEventArgs)
' <snippet22>
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As 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>
End Sub
Private Sub Method23(ByVal e As PaintEventArgs)
' <snippet23>
Dim rect As New Rectangle(0, 0, 50, 50)
Dim pen As 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>
End Sub
' 3a4c07cb-a40a-4d14-ad35-008f531910a8
' How to: Use Hit Testing with a Region
Private Sub Method31(ByVal e As PaintEventArgs)
' <snippet31>
Dim point As 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.
Dim solidBrush As New SolidBrush(Color.Black)
Dim region1 As New [Region](New Rectangle(50, 0, 50, 150))
Dim region2 As 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) Then
' 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)
End If
e.Graphics.FillRegion(solidBrush, region1)
' </snippet31>
End Sub
' 43d121b4-e14c-4901-b25c-2d6c25ba4e29
' How to: Use Clipping with a Region
Private Sub Method41(ByVal e As PaintEventArgs)
' <snippet41>
' Create a path that consists of a single polygon.
Dim polyPoints As Point() = { _
New Point(10, 10), _
New Point(150, 10), _
New Point(100, 75), _
New Point(100, 150)}
Dim path As New GraphicsPath()
path.AddPolygon(polyPoints)
' Construct a region based on the path.
Dim [region] As New [Region](path)
' Draw the outline of the region.
Dim pen As 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.
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
fontFamily, _
36, _
FontStyle.Bold, _
GraphicsUnit.Pixel)
Dim solidBrush As 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>
End Sub
' a0d9f178-43a4-4323-bb5a-d3e3f77ae6c1
' Using Nested Graphics Containers
Private Sub Method61(ByVal e As PaintEventArgs)
' <snippet61>
Dim graphics As Graphics = e.Graphics
Dim pen As New Pen(Color.Red)
Dim graphicsContainer As 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>
End Sub
Private Sub Method62(ByVal e As PaintEventArgs)
' <snippet62>
Dim graphics As Graphics = e.Graphics
Dim graphicsContainer As GraphicsContainer
Dim redPen As New Pen(Color.Red, 2)
Dim bluePen As New Pen(Color.Blue, 2)
Dim aquaBrush As New SolidBrush(Color.FromArgb(255, 180, 255, 255))
Dim greenBrush As 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.
Dim path As New GraphicsPath()
path.AddEllipse(75, 50, 100, 150)
' Construct a region based on the path.
Dim [region] As 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>
End Sub
Private Sub Method63(ByVal e As PaintEventArgs)
' <snippet63>
Dim graphics As Graphics = e.Graphics
Dim innerContainer As GraphicsContainer
Dim outerContainer As GraphicsContainer
Dim brush As New SolidBrush(Color.Blue)
Dim fontFamily As New FontFamily("Times New Roman")
Dim font As 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>
End Sub
End Class
@@ -0,0 +1,83 @@
'<snippet0>
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Private printButton As Button
'<snippet8>
Private printDocument1 As New PrintDocument()
Private stringToPrint As String
'</snippet8>
Public Sub New()
Me.printButton = New System.Windows.Forms.Button()
Me.printButton.Location = New System.Drawing.Point(12, 51)
Me.printButton.Size = New System.Drawing.Size(75, 23)
Me.printButton.Text = "Print"
Me.ClientSize = New System.Drawing.Size(292, 266)
End Sub
Private Sub ReadFile()
'<snippet1>
Dim docName As String = "testPage.txt"
Dim docPath As String = "c:\"
printDocument1.DocumentName = docName
Dim stream As New FileStream(docPath + docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
stringToPrint = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
'</snippet1>
End Sub
'<snippet2>
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As PrintPageEventArgs)
Dim charactersOnPage As Integer = 0
Dim linesPerPage As Integer = 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, Me.Font, e.MarginBounds.Size, _
StringFormat.GenericTypographic, charactersOnPage, linesPerPage)
' Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, Me.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
End Sub
'</snippet2>
Private Sub printButton_Click(ByVal sender As Object, ByVal e As EventArgs)
ReadFile()
'<snippet5>
printDocument1.Print()
'</snippet5>
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
'</snippet0>

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