<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Crows Programming &#187; C#</title>
	<atom:link href="http://www.crowsprogramming.com/archives/category/programming/csharp/feed" rel="self" type="application/rss+xml" />
	<link>http://www.crowsprogramming.com</link>
	<description>Computer Programming and Random Blurbs</description>
	<lastBuildDate>Mon, 19 Sep 2011 20:53:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Runtime Scripting in .Net</title>
		<link>http://www.crowsprogramming.com/archives/99</link>
		<comments>http://www.crowsprogramming.com/archives/99#comments</comments>
		<pubDate>Thu, 01 Oct 2009 04:49:40 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=99</guid>
		<description><![CDATA[The ability to ship source code with your product that can be compiled or interpreted at runtime is a very valuable asset. Video games do this all the time with things like AI allowing the end-user to easily mod the game. In compiled languages like C++, this technique is highly advantageous as it allows you [...]]]></description>
			<content:encoded><![CDATA[<p>The ability to ship source code with your product that can be compiled or interpreted at runtime is a very valuable asset.  Video games do this all the time with things like AI allowing the end-user to easily mod the game. In compiled languages like C++, this technique is highly advantageous as it allows you to avoid the costly compile-link cycle for every small change to a source file. This is also helpful in an environment where creating a new build, generating the installer, and deploying it is overkill or difficult to achieve. In this article we will examine how you can achieve this from .Net programs consuming a C# or VB.Net script.  I’ll refer to this as &#8220;scripting&#8221;, even though an unambiguous definition of a &#8220;script&#8221; is somewhat difficult to nail down.</p>
<p>Using a C# or VB script from a .Net language is actually very simple. The basic idea is to read in a source file, which could come from the network or disk, and compile it into a temporary assembly on file or IL in memory. Then you can instantiate types from the script file and use them just as easily as any other types already defined. Normally the hard part in this process is locating and invoking the proper compiler. Luckily, we can compile IL code using a CodeDomProvider like CSharpCodeProvider. And, since these types are part of the .Net framework we know they are available on the end-user PC! Life is great eh?</p>
<p>Ok, so first make sure you have referenced the following namespaces:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.CodeDom.Compiler</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">Microsoft.CSharp</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">Microsoft.VisualBasic</span><span style="color: #008000;">;</span></pre></div></div>

<p>Next you need to setup the compiler parameters. These are simply the options given to the compiler such as whether to create the resulting assembly in memory or if debug information should be included in the generated code. You can do this with the CompilerParameters type. Here is an example for creating an in memory assembly with debug information:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> CompilerParameters cparams <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
 cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">GenerateInMemory</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
 cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">IncludeDebugInformation</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
 cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">CompilerOptions</span> <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot; /debug:pdbonly&quot;</span><span style="color: #008000;">;</span>
&nbsp;
 cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">TreatWarningsAsErrors</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
 cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">GenerateExecutable</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span></pre></div></div>

<p>You would also want to add any references that your code needs using CompilerParameters. ReferencedAssemblies. So, after you have the compiler options set you need to actually invoke the C# or Visual Basic compiler. You do this by creating a CodeDomCompiler of the appropriate type:</p>
<p>VBCodeProvider – for Visual Basic<br />
CSharpCodeProvider – for C Sharp</p>
<p>Then you can use the provider to compile an assembly like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">CodeDomProvider provider <span style="color: #008000;">=</span> CSharpCodeProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
CompilerResults result <span style="color: #008000;">=</span> provider<span style="color: #008000;">.</span><span style="color: #0000FF;">CompileAssemblyFromFile</span><span style="color: #008000;">&#40;</span>cparams, script<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Where cparams are your compiler parameters and result is well, your results. Within results you will find out if the compilation was successful or generated warnings. It will also give you access to the resulting assembly. You can check for errors using results.Errors.HasErrors and reference the assembly with results.CompiledAssembly.</p>
<p><span id="more-99"></span></p>
<p>Now that you have a compiled assembly in memory, there is one last issue to address. How do you instantiate types from the assembly? The easiest way to attack the problem is to create an interface that your application can access and derive a type from that interface in your script. I’ve created a full example below (explained in code comments) to illustrate the technique I am talking about.</p>
<h2> C# Example </h2>
<h3> Main application &#8211; Script.cs</h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.CodeDom.Compiler</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">Microsoft.CSharp</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">Microsoft.VisualBasic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ScriptingExample
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Script
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> LoadedType LoadScript<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> script, <span style="color: #6666cc; font-weight: bold;">string</span> referenceString<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">where</span> LoadedType<span style="color: #008000;">:</span><span style="color: #6666cc; font-weight: bold;">class</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// this will load/compile the script source file, &quot;script&quot;, and return a type of LoadedType</span>
            <span style="color: #008080; font-style: italic;">// it is assumed that a type of &quot;LoadedType&quot; is defined in the script</span>
            <span style="color: #008080; font-style: italic;">// the referenceString is a comma delimited string identifying all references needed by the script</span>
            <span style="color: #008080; font-style: italic;">// e.g. &quot;System.dll,System.Windows.Forms.dll&quot;</span>
            <span style="color: #008080; font-style: italic;">// either the VB or C# compiler will be invoked, based upon the file extenstion .vb or .cs</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and compile the script</span>
            CompilerParameters cparams <span style="color: #008000;">=</span> CreateCompilerParameters<span style="color: #008000;">&#40;</span>referenceString<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            CompilerResults results <span style="color: #008000;">=</span> CompileScript<span style="color: #008000;">&#40;</span>script, cparams<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// check for errors</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>results<span style="color: #008000;">.</span><span style="color: #0000FF;">Errors</span><span style="color: #008000;">.</span><span style="color: #0000FF;">HasErrors</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #6666cc; font-weight: bold;">string</span> e <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>CompilerError error <span style="color: #0600FF; font-weight: bold;">in</span> results<span style="color: #008000;">.</span><span style="color: #0000FF;">Errors</span><span style="color: #008000;">&#41;</span>
                    e <span style="color: #008000;">+=</span> <span style="color: #008000;">&#40;</span>error<span style="color: #008000;">.</span><span style="color: #0000FF;">ErrorText</span> <span style="color: #008000;">+</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ERROR IN SCRIPT: &quot;</span> <span style="color: #008000;">+</span> Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">NewLine</span> <span style="color: #008000;">+</span> e<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// find the &quot;exported&quot; type to load</span>
            LoadedType scriptObject <span style="color: #008000;">=</span> FindScriptObject<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>results<span style="color: #008000;">.</span><span style="color: #0000FF;">CompiledAssembly</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>scriptObject <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;CAN'T LOAD SCRIPT, TARGET TYPE NOT IMPLEMENTED IN SCRIPT.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> scriptObject<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> CompilerResults CompileScript<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> script, CompilerParameters cparams<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// compiles the script using the specified parameters</span>
            <span style="color: #008080; font-style: italic;">// either the VB or C# compiler will be invoked, based upon the file extenstion .vb or .cs</span>
            CodeDomProvider provider <span style="color: #008000;">=</span> GetCompiler<span style="color: #008000;">&#40;</span>script<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            CompilerResults result <span style="color: #008000;">=</span> provider<span style="color: #008000;">.</span><span style="color: #0000FF;">CompileAssemblyFromFile</span><span style="color: #008000;">&#40;</span>cparams, script<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        CodeDomProvider GetCompiler<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> script<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// returns the correct compiler to use based on the file extension of the script</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> extension <span style="color: #008000;">=</span> Path<span style="color: #008000;">.</span><span style="color: #0000FF;">GetExtension</span><span style="color: #008000;">&#40;</span>script<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>extension <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;.vb&quot;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> VBCodeProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>extension <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;.cs&quot;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> CSharpCodeProvider<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;UNKNOWN SCRIPT TYPE&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> LoadedType FindScriptObject<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>Assembly assembly<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">where</span> LoadedType <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">class</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// attempts to locate the type &quot;LoadedType&quot; within the assembly that was created from the &quot;script&quot;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>Type t <span style="color: #0600FF; font-weight: bold;">in</span> assembly<span style="color: #008000;">.</span><span style="color: #0000FF;">GetTypes</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>LoadedType<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #008000;">&#40;</span>t<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #0600FF; font-weight: bold;">return</span> Activator<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateInstance</span><span style="color: #008000;">&#40;</span>t<span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> LoadedType<span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">default</span><span style="color: #008000;">&#40;</span>LoadedType<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> CompilerParameters CreateCompilerParameters<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> referenceString<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// creates compiler parameters to generate an in memory assembly, with debug</span>
            <span style="color: #008080; font-style: italic;">// symbols if this is a debug build</span>
            <span style="color: #008080; font-style: italic;">// the referenceString is a comma delimited string identifying all references needed by the script</span>
            CompilerParameters cparams <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">GenerateInMemory</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080;">#if DEBUG</span>
                <span style="color: #008080; font-style: italic;">// create debug symbols if this is a debug build</span>
                cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">IncludeDebugInformation</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
                cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">CompilerOptions</span> <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot; /debug:pdbonly&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #008080;">#endif</span>
&nbsp;
            cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">TreatWarningsAsErrors</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
            cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">GenerateExecutable</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span> 
&nbsp;
            <span style="color: #008080; font-style: italic;">// seperate reference string</span>
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> references <span style="color: #008000;">=</span> referenceString<span style="color: #008000;">.</span><span style="color: #0000FF;">Split</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">','</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> reference <span style="color: #0600FF; font-weight: bold;">in</span> references<span style="color: #008000;">&#41;</span>
                cparams<span style="color: #008000;">.</span><span style="color: #0000FF;">ReferencedAssemblies</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>reference<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> cparams<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3> App Showing How to Use Script.cs </h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ComponentModel</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Data</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Drawing</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ScriptingExample
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// we have to define an interface so we know how to &quot;talk&quot; to</span>
    <span style="color: #008080; font-style: italic;">// the script, that is, there must be a type that we *know* the</span>
    <span style="color: #008080; font-style: italic;">// script implements so we can call methods on it</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">interface</span> MyScript
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">void</span> Execute<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> Form1 <span style="color: #008000;">:</span> Form
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> Form1<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Form1_Load<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, EventArgs e<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// just populate the combo box with all &quot;scripts&quot; located in the directory &quot;Scripts&quot;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> file <span style="color: #0600FF; font-weight: bold;">in</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">GetFiles</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Scripts&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                comboBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>file<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>comboBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
                comboBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">SelectedIndex</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
            <span style="color: #008000;">&#123;</span>
                button1<span style="color: #008000;">.</span><span style="color: #0000FF;">Enabled</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
                comboBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">Enabled</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> button1_Click<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, EventArgs e<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// load the script, which contains a type that implements MyScript</span>
            <span style="color: #008080; font-style: italic;">// and call the execute method on it</span>
            Script s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Script<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// these are the references the script will need, we must reference this executable</span>
            <span style="color: #008080; font-style: italic;">// because the script needs to see the MyScript data type</span>
            <span style="color: #008080; font-style: italic;">// this is just a sample, in a real application such types would be defined in an assembly dll</span>
            <span style="color: #008080; font-style: italic;">// that is shared between the app consuming the script and the script itself</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> references <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;System.dll,System.Windows.Forms.dll,&quot;</span> <span style="color: #008000;">+</span> Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentDirectory</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\\</span>ScriptingExample.exe&quot;</span><span style="color: #008000;">;</span>
&nbsp;
            MyScript script <span style="color: #008000;">=</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">LoadScript</span><span style="color: #008000;">&lt;</span>MyScript<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>comboBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">SelectedItem</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span>, references<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            script<span style="color: #008000;">.</span><span style="color: #0000FF;">Execute</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3> A VB and C# Script</h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ScriptingExample<span style="color: #008000;">.</span><span style="color: #0000FF;">Scripts</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> CSharpScript <span style="color: #008000;">:</span> MyScript
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Execute<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;I AM A C# SCRIPT&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="vbnet" style="font-family:monospace;"><span style="color: #0600FF;">Imports</span> System
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Text</span>
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>
&nbsp;
<span style="color: #0600FF;">Namespace</span> ScriptingExample.<span style="color: #0000FF;">Scripts</span>
    <span style="color: #FF8000;">Public</span> <span style="color: #0600FF;">Class</span> VBScript
        <span style="color: #0600FF;">Implements</span> MyScript
        <span style="color: #FF8000;">Public</span> <span style="color: #0600FF;">Sub</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">Implements</span> MyScript.<span style="color: #0000FF;">Execute</span>
            MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;I AM A VB SCRIPT!!&quot;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Sub</span>
    <span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Class</span>
<span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Namespace</span></pre></div></div>

<h2>Conclusion</h2>
<p>And that&#8217;s it! A very simple technique that can be used in many interesting ways. I&#8217;ve included a link to a Visual Studio project containing an implementation using the above information. The project can be found <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/09/scriptingexample.zip"> here </a> As always, let me know if you have any questions or ideas!</p>
<p>See ya next time!</p>
<fb:like href='http://www.crowsprogramming.com/archives/99' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/99/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using Ini Files In C#</title>
		<link>http://www.crowsprogramming.com/archives/95</link>
		<comments>http://www.crowsprogramming.com/archives/95#comments</comments>
		<pubDate>Thu, 16 Jul 2009 23:26:32 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=95</guid>
		<description><![CDATA[An Initialization, or Ini file, is a common text based file format commonly used on the Windows platform. Today its mostly been succeeded in favor of XML files for application configuration and persisting user data. Never the less, these files still exist and are in use by many applications. In this post, we will explore [...]]]></description>
			<content:encoded><![CDATA[<p>An Initialization, or <b>Ini</b> file, is a common text based file format commonly used on the Windows platform. Today its mostly been succeeded in favor of XML files for application configuration and persisting user data. Never the less, these files still exist and are in use by many applications. In this post, we will explore how to work with Ini files via C#.</p>
<p>The structure of an Ini file is very simple and straight forward. You have three primary types of information: sections, parameters, and values. They look like this:</p>
<p>[SectionA]<br />
Parameter1=value1<br />
Parameter2=value2</p>
<p>[SectionB]<br />
Parameter1=value1</p>
<p>Below we will create a class to read this data from a file. Keep in mind as you look at this C# Ini file implementation that this is just one way to do it. You could for example, create a much more concise solution using regular expressions, etc.</p>
<h2>Parsing the Data</h2>
<p>The first thing we should do if figure out how to get the data from the Ini file. We could read in all the text and manually parse the file; however there is an easier approach. The Win32 API contains a function called <i>GetPrivateProfileString</i> that we can use specifically for this task. We can use it to directly obtain the sections, parameters, and values. For a more detailed description of the GetPrivateProfileString function, check out <a href="http://msdn.microsoft.com/en-us/library/ms724353%28VS.85%29.aspx">this link on MSDN</a>.</p>
<p>To use GetPrivateProfileString in C#, we need only reference it using the <i>DLLImport</i> attribute with the correct function signature.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Kernel32.dll&quot;</span>, EntryPoint <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;GetPrivateProfileStringW&quot;</span>, SetLastError <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>, CharSet <span style="color: #008000;">=</span> CharSet<span style="color: #008000;">.</span><span style="color: #0000FF;">Unicode</span>, ExactSpelling <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>, CallingConvention <span style="color: #008000;">=</span> CallingConvention<span style="color: #008000;">.</span><span style="color: #0000FF;">StdCall</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> <span style="color: #6666cc; font-weight: bold;">int</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> lpAppName,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpKeyName,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpDefault,
                                                         <span style="color: #008000;">&#91;</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #008000;">&#93;</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> lpReturnString,
                                                         <span style="color: #6666cc; font-weight: bold;">int</span> nSize,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpFilename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2> Reading from an Ini File</h2>
<p>First, to make our job a little easier we will wrap the call to GetPrivateProfileString with our own method so that we can handle all of the details. Here is the wrapper:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> appName, <span style="color: #6666cc; font-weight: bold;">string</span> keyName, <span style="color: #6666cc; font-weight: bold;">string</span> defaultName, <span style="color: #6666cc; font-weight: bold;">string</span> inifile<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// the file inifile should exist as it's validated in the class constructor, however GetPrivateProfileString does not lock the file hence it could be locked or deleted by</span>
            <span style="color: #008080; font-style: italic;">// another process between calls to this method</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// used to tell if we successfully read all requested data from the file </span>
            <span style="color: #008080; font-style: italic;">// from MSDN:</span>
            <span style="color: #008080; font-style: italic;">//  If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.</span>
            <span style="color: #008080; font-style: italic;">//  If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.</span>
            <span style="color: #6666cc; font-weight: bold;">int</span> sizeReadOffset <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>appName <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> keyName <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">:</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and read the entire amount of data from the ini file</span>
            <span style="color: #6666cc; font-weight: bold;">int</span> sizeRead <span style="color: #008000;">=</span> Kernel32<span style="color: #008000;">.</span><span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #008000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if unable to read all of the data because the buffer is to small, increase the size and try again, but only allow memory to increase up to _readBufferMaxSize</span>
            <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>sizeRead <span style="color: #008000;">&gt;=</span> _readBufferSize <span style="color: #008000;">-</span> sizeReadOffset<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">&#40;</span>_readBufferSize <span style="color: #008000;">&lt;</span> _readBufferMaxSize<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                _readBufferSize <span style="color: #008000;">+=</span> <span style="color: #FF0000;">512</span><span style="color: #008000;">;</span>
                _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span>_readBufferSize<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
                sizeRead <span style="color: #008000;">=</span> Kernel32<span style="color: #008000;">.</span><span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #008000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if memory consumption exceeded _readBufferMaxSize then we have a problem</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_readBufferSize <span style="color: #008000;">&gt;=</span> _readBufferMaxSize<span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> FileLoadException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniLoad&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the buffer returned from GetPrivateProfileString will be null terminated C-strings followed by a double null at the end - so split the strings on the nulls</span>
            <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> sep <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
            sep<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">'<span style="color: #008080; font-weight: bold;">\0</span>'</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span> s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#40;</span>_readBuffer, <span style="color: #FF0000;">0</span>, sizeRead<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> result <span style="color: #008000;">=</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">Split</span><span style="color: #008000;">&#40;</span>sep, StringSplitOptions<span style="color: #008000;">.</span><span style="color: #0000FF;">RemoveEmptyEntries</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span></pre></div></div>

<p>Here, the MSDN terminology refers to what I call a section as an appName and what I refer to as a paramter as a keyName.</p>
<p>This method has a lot going on but is very easy to use. To get an array of strings containing all of the section names you simply say:<br />
<span id="more-95"></span></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And, to get an array of all parameter names for a particular section you would say:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span>sectionName, <span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, inifileName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And finally, to get a parameter value you could say:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span>sectionName, parameterName, <span style="color: #0600FF; font-weight: bold;">null</span>, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And the value is stored in the first element of the returned array.</p>
<h2>Putting it All Together</h2>
<p>So now we can put together a simple class encapsulating the above functionality. You can use this class as follows:</p>
<p>Given an Ini file:</p>
<p>[SectionA]<br />
Parameter1=value1<br />
Parameter2=value2</p>
<p>[SectionB]<br />
Parameter1=value1</p>
<p>You could,</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">            INIFile file <span style="color: #008000;">=</span>  <span style="color: #008000;">new</span> INIFile<span style="color: #008000;">&#40;</span>Directory<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentDirectory</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> Path<span style="color: #008000;">.</span><span style="color: #0000FF;">DirectorySeparatorChar</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;MyInifile.ini&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span> a1 <span style="color: #008000;">=</span> file<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;SectionA&quot;</span>,<span style="color: #666666;">&quot;Parameter1&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value1&quot;</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> a2 <span style="color: #008000;">=</span> file<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;SectionA&quot;</span>,<span style="color: #666666;">&quot;Parameter2&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value2&quot;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span> b1 <span style="color: #008000;">=</span> file<span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;SectionB&quot;</span>, <span style="color: #666666;">&quot;Parameter1&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value1&quot;</span></pre></div></div>

<p>Have fun playing with it. You could easily add the ability to write new sections and parameters as well. If you make some changes, find some bugs, or just plain find it useful let me know. I am always interested.</p>
<p>Here is the complete code listing for the class. You can <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/07/inifile.cs">download it here</a> or just copy and paste it.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Contains native Win32 API methods found in Kernel32. </span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> Kernel32
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Retrieves a string from the specified section in an initialization file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpAppName&quot;&gt;The name of the section containing the key name. If this parameter is NULL, the GetPrivateProfileString function copies all section names in the file to the supplied buffer.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpKeyName&quot;&gt;The name of the key whose associated string is to be retrieved. If this parameter is NULL, all key names in the section specified by the lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpDefault&quot;&gt;A default string. If the lpKeyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the lpReturnedString buffer. If this parameter is NULL, the default is an empty string, &quot;&quot;.</span>
        <span style="color: #008080; font-style: italic;">///                         &lt;para&gt;Avoid specifying a default string with trailing blank characters. The function inserts a null character in the lpReturnedString buffer to strip any trailing blanks.&lt;/para&gt;&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpReturnString&quot;&gt;A pointer to the buffer that receives the retrieved string.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;nSize&quot;&gt;The size of the buffer pointed to by the lpReturnedString parameter, in characters.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpFilename&quot;&gt;The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The return value is the number of characters copied to the buffer, not including the terminating null character.&lt;/returns&gt;</span>
        <span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Kernel32.dll&quot;</span>, EntryPoint <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;GetPrivateProfileStringW&quot;</span>, SetLastError <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>, CharSet <span style="color: #008000;">=</span> CharSet<span style="color: #008000;">.</span><span style="color: #0000FF;">Unicode</span>, ExactSpelling <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>, CallingConvention <span style="color: #008000;">=</span> CallingConvention<span style="color: #008000;">.</span><span style="color: #0000FF;">StdCall</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> <span style="color: #6666cc; font-weight: bold;">int</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> lpAppName,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpKeyName,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpDefault,
                                                         <span style="color: #008000;">&#91;</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #008000;">&#93;</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> lpReturnString,
                                                         <span style="color: #6666cc; font-weight: bold;">int</span> nSize,
                                                         <span style="color: #6666cc; font-weight: bold;">string</span> lpFilename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Represents the &lt;i&gt;common&lt;/i&gt; INI file format consisting of parameter-value pairs grouped by sections.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> INIFile
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080;">#region Nested Types</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> CaseSensitiviy
        <span style="color: #008000;">&#123;</span>
            CaseInsensitive,
            CaseSensitive
        <span style="color: #008000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Properties</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Provides the string value of parameter belonging to the specified section. The section and parameter must exist.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section the parameter belongs to.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter containing the value.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.ArgumentException&quot;&gt;Thrown if either the section or parameter name do not exist.&lt;/exception&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The value of the parameter.&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#91;</span><span style="color: #6666cc; font-weight: bold;">string</span> sectionName, <span style="color: #6666cc; font-weight: bold;">string</span> parameterName<span style="color: #008000;">&#93;</span>
        <span style="color: #008000;">&#123;</span>
            get
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_sections<span style="color: #008000;">.</span><span style="color: #0000FF;">ContainsKey</span><span style="color: #008000;">&#40;</span>sectionName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_sections<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ContainsKey</span><span style="color: #008000;">&#40;</span>parameterName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                        <span style="color: #0600FF; font-weight: bold;">return</span> _sections<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>parameterName<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
                    <span style="color: #0600FF; font-weight: bold;">else</span>
                        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
                <span style="color: #0600FF; font-weight: bold;">else</span>
                    <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Specifies what case sensitivity mode is being used when looking up section and parameter names.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> CaseSensitiviy CaseSensitivity
        <span style="color: #008000;">&#123;</span>
            get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _caseSensitivity<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Events</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Constructors</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Loads the specified INI file. By default, all searches for section and parameter names will be case sensitive.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;The file name and path to the INI file. If this parameter does not contain a full path to the file, the method will search the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.IO.FileNotFoundException&quot;&gt;Thrown if filename could not be found and doesn't exist in the Window directory.&lt;/exception&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> INIFile<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#40;</span>filename, CaseSensitiviy<span style="color: #008000;">.</span><span style="color: #0000FF;">CaseSensitive</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Loads the specified INI file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;The file name and path to the INI file. If this parameter does not contain a full path to the file, the method will search the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sensitivity&quot;&gt;Specifies if letter case should be accounted for when looking up section and parameter names.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.IO.FileNotFoundException&quot;&gt;Thrown if filename could not be found and doesn't exist in the Window directory.&lt;/exception&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> INIFile<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename, CaseSensitiviy sensitivity<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// make sure the file exists, directly, or in the Windows directory</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>File<span style="color: #008000;">.</span><span style="color: #0000FF;">Exists</span><span style="color: #008000;">&#40;</span>filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>File<span style="color: #008000;">.</span><span style="color: #0000FF;">Exists</span><span style="color: #008000;">&#40;</span>Path<span style="color: #008000;">.</span><span style="color: #0000FF;">Combine</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">ExpandEnvironmentVariables</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;%WinDir%&quot;</span><span style="color: #008000;">&#41;</span>, filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> FileNotFoundException<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// save local state</span>
            _caseSensitivity <span style="color: #008000;">=</span> sensitivity<span style="color: #008000;">;</span>
            _readBufferSize <span style="color: #008000;">=</span> _readBufferDefaultSize<span style="color: #008000;">;</span>
            _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span>_readBufferSize<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// read all section names</span>
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, filename<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the data is stored in a dictionary, we must tell it if case sensitivity is important</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_caseSensitivity <span style="color: #008000;">==</span> CaseSensitiviy<span style="color: #008000;">.</span><span style="color: #0000FF;">CaseInsensitive</span><span style="color: #008000;">&#41;</span>
                _sections <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span>StringComparer<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCultureIgnoreCase</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                _sections <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// now, read in all parameters and values for each section name we located</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> s <span style="color: #0600FF; font-weight: bold;">in</span> raw<span style="color: #008000;">&#41;</span>
                ReadSection<span style="color: #008000;">&#40;</span>filename, s, _sections<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Public Methods</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Checks to see if a given section exists in the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The section name to check for.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;True if the section exists, false if not.&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> DoesSectionExist<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> sectionName<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> _sections<span style="color: #008000;">.</span><span style="color: #0000FF;">ContainsKey</span><span style="color: #008000;">&#40;</span>sectionName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Checks to see if a given parameter exists for a section.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section containing the parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter to check for.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;True if the parameter exists, false if not.&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> DoesParameterExist<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> sectionName, <span style="color: #6666cc; font-weight: bold;">string</span> parameterName<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>DoesSectionExist<span style="color: #008000;">&#40;</span>sectionName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> _sections<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ContainsKey</span><span style="color: #008000;">&#40;</span>parameterName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Private Methods</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Reads all parameters and values for a given section within the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The ini file to read from.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section to read.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;storage&quot;&gt;A dictionary containing an entry for the section that will be populated with the resulting parameters/values.&lt;/param&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> ReadSection<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> inifile, <span style="color: #6666cc; font-weight: bold;">string</span> sectionName, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;&gt;</span> storage<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// create the parameter/value dictionary for the section entry</span>
            <span style="color: #008080; font-style: italic;">// it is assumed that the callers logic created/validated storage[sectionName] -- we will not check again here</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_caseSensitivity <span style="color: #008000;">==</span> CaseSensitiviy<span style="color: #008000;">.</span><span style="color: #0000FF;">CaseInsensitive</span><span style="color: #008000;">&#41;</span>
                storage<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>StringComparer<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCultureIgnoreCase</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                storage<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span>sectionName, <span style="color: #0600FF; font-weight: bold;">null</span>, <span style="color: #0600FF; font-weight: bold;">null</span>, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// now read in the values for the parameters that we found</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> s <span style="color: #0600FF; font-weight: bold;">in</span> raw<span style="color: #008000;">&#41;</span>
                ReadParameter<span style="color: #008000;">&#40;</span>inifile, sectionName, s, storage<span style="color: #008000;">&#91;</span>sectionName<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Reads the value of a parameter in a given section within the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The ini file to read from.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section containing the parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter to read.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;storage&quot;&gt;The dictionary that the parameter value will be written to.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.ArgumentException&quot;&gt;Thrown if more than 1 value is associated with a single parameter.&lt;/exception&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> ReadParameter<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> inifile, <span style="color: #6666cc; font-weight: bold;">string</span> sectionName, <span style="color: #6666cc; font-weight: bold;">string</span> parameterName, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> storage<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// get the param value</span>
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span>sectionName, parameterName, <span style="color: #0600FF; font-weight: bold;">null</span>, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// store the resulting value, if more than 1 value comes back for the parameter throw an exception, not sure how to parse that scenario</span>
            <span style="color: #008080; font-style: italic;">// if no values come back just use an empty string by default</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>raw<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>raw<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
                storage<span style="color: #008000;">&#91;</span>parameterName<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
                storage<span style="color: #008000;">&#91;</span>parameterName<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> raw<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Wrapper around the Win32 function GetPrivateProfileString to make it nicer and more robust.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;appName&quot;&gt;The name of the section containing the key name. If this parameter is null, all section names will be returned.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;keyName&quot;&gt;The name of the key whose associated string is to be retrieved. If this parameter is null, all key names in the section will be returned.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;defaultName&quot;&gt;A default string. If the keyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the </span>
        <span style="color: #008080; font-style: italic;">///                           returned value. If this parameter is null, the default is an empty string, &quot;&quot;.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The path and file name of the INI file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;An array of string containing either section names, parameter names, or values corresponding to appName and keyName.&lt;/returns&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;FileLoadException&quot;&gt;&lt;/exception&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> GetPrivateProfileString<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> appName, <span style="color: #6666cc; font-weight: bold;">string</span> keyName, <span style="color: #6666cc; font-weight: bold;">string</span> defaultName, <span style="color: #6666cc; font-weight: bold;">string</span> inifile<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// the file inifile should exist as it's validated in the class constructor, however GetPrivateProfileString does not lock the file hence it could be locked or deleted by</span>
            <span style="color: #008080; font-style: italic;">// another process between calls to this method</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// used to tell if we successfully read all requested data from the file </span>
            <span style="color: #008080; font-style: italic;">// from MSDN:</span>
            <span style="color: #008080; font-style: italic;">//  If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.</span>
            <span style="color: #008080; font-style: italic;">//  If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.</span>
            <span style="color: #6666cc; font-weight: bold;">int</span> sizeReadOffset <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>appName <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> keyName <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">:</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and read the entire amount of data from the ini file</span>
            <span style="color: #6666cc; font-weight: bold;">int</span> sizeRead <span style="color: #008000;">=</span> Kernel32<span style="color: #008000;">.</span><span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #008000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if unable to read all of the data because the buffer is to small, increase the size and try again, but only allow memory to increase up to _readBufferMaxSize</span>
            <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>sizeRead <span style="color: #008000;">&gt;=</span> _readBufferSize <span style="color: #008000;">-</span> sizeReadOffset<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">&#40;</span>_readBufferSize <span style="color: #008000;">&lt;</span> _readBufferMaxSize<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                _readBufferSize <span style="color: #008000;">+=</span> <span style="color: #FF0000;">512</span><span style="color: #008000;">;</span>
                _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span>_readBufferSize<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
                sizeRead <span style="color: #008000;">=</span> Kernel32<span style="color: #008000;">.</span><span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #008000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if memory consumption exceeded _readBufferMaxSize then we have a problem</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_readBufferSize <span style="color: #008000;">&gt;=</span> _readBufferMaxSize<span style="color: #008000;">&#41;</span>
                <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> FileLoadException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniLoad&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the buffer returned from GetPrivateProfileString will be null terminated C-strings followed by a double null at the end - so split the strings on the nulls</span>
            <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> sep <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
            sep<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">'<span style="color: #008080; font-weight: bold;">\0</span>'</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span> s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#40;</span>_readBuffer, <span style="color: #FF0000;">0</span>, sizeRead<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> result <span style="color: #008000;">=</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">Split</span><span style="color: #008000;">&#40;</span>sep, StringSplitOptions<span style="color: #008000;">.</span><span style="color: #0000FF;">RemoveEmptyEntries</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Fields</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Stores the sections from the Ini file. The section name is the key. The value is another dictionary containing the parameter values, keyed on the parameter name.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;&gt;</span> _sections<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Determines if case is ignored or not when referencing section and parameter names.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> CaseSensitiviy _caseSensitivity<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Holds the information from the last read of the ini file. The buffer is overwritten with sections, parameters, or values on each call to GetPrivateProfileString.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> _readBuffer<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The size, in bytes, of _readBuffer.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> _readBufferSize<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The starting size of _readBuffer, in bytes.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> _readBufferDefaultSize <span style="color: #008000;">=</span> <span style="color: #FF0000;">1024</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The maximum size _readBuffer is allowed to grow to in order to hold all information obtained from GetPrivateProfileString.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> _readBufferMaxSize <span style="color: #008000;">=</span> <span style="color: #FF0000;">4096</span><span style="color: #008000;">;</span>
        <span style="color: #008080;">#endregion</span>
    <span style="color: #008000;">&#125;</span></pre></div></div>

<fb:like href='http://www.crowsprogramming.com/archives/95' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/95/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Accessing the System Task Bar in C#</title>
		<link>http://www.crowsprogramming.com/archives/88</link>
		<comments>http://www.crowsprogramming.com/archives/88#comments</comments>
		<pubDate>Sun, 10 May 2009 06:56:18 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=88</guid>
		<description><![CDATA[In this post I’ll show you how to access the system taskbar and obtain information like its location, size, etc. You may find yourself needing to do something like this if you had a &#8220;popup&#8221; window for instance that is always supposed to &#8220;pop up&#8221; from the system tray. This is a common feature in [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I’ll show you how to access the system taskbar and obtain information like its location, size, etc. You may find yourself needing to do something like this if you had a &#8220;popup&#8221; window for instance that is always supposed to &#8220;pop up&#8221; from the system tray. This is a common feature in many of today’s applications; however the task bar may be docked somewhere other than the bottom of the screen or maybe even on a different monitor in a multi-monitor setup.</p>
<h2>The Taskbar is an APPBAR</h2>
<p>First, the task bar is considered an appbar (or <a href="http://msdn.microsoft.com/en-us/library/cc144177(VS.85).aspx">desktop application toolbar</a>) albeit with some special restrictions. Being an appbar we can talk to it with the Win32 API function <i><b>SHAppBarMessage</b></i>. SHAppBarMessage allows us to send a message to the system to get or set information about a registered appbar. The necessary C# definitions to access the function are as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>StructLayout<span style="color: #008000;">&#40;</span>LayoutKind<span style="color: #008000;">.</span><span style="color: #0000FF;">Sequential</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">struct</span> RECT
<span style="color: #008000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> left<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> top<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> right<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> bottom<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>StructLayout<span style="color: #008000;">&#40;</span>LayoutKind<span style="color: #008000;">.</span><span style="color: #0000FF;">Sequential</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">struct</span> APPBARDATA
<span style="color: #008000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> Int32 cbSize<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> IntPtr hWnd<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> Int32 uCallbackMessage<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> ABEdge uEdge<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> RECT rc<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">public</span> IntPtr lParam<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABMsg
<span style="color: #008000;">&#123;</span>
ABM_NEW <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABM_REMOVE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABM_QUERYPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABM_SETPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
      ABM_GETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>,
      ABM_GETTASKBARPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>,
      ABM_ACTIVATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">6</span>,
      ABM_GETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span>,
      ABM_SETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">8</span>,
      ABM_WINDOWPOSCHANGED <span style="color: #008000;">=</span> <span style="color: #FF0000;">9</span>,
      ABM_SETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABEdge
<span style="color: #008000;">&#123;</span>
ABE_LEFT <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABE_TOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABE_RIGHT <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABE_BOTTOM <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABState
<span style="color: #008000;">&#123;</span>
ABS_MANUAL <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABS_AUTOHIDE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABS_ALWAYSONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABS_AUTOHIDEANDONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;shell32.dll&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg dwMessage, <span style="color: #008000;">&#91;</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">ref</span> APPBARDATA pData<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Using SHAppBarMessage</h2>
<p>In order to use SHAppBarMessage we must first fill out the APPBAR struct with at least the cbSize and hWnd members. For hWnd we need to get the handle to the system taskbar window. It just so happens that you can use the FindWindow API function with a system class name of &#8220;Shell_TrayWnd&#8221; to get the required handle. Of course, to the best of my knowledge the class name &#8220;Shell_TrayWnd&#8221; is not a &#8220;documented&#8221; part of the Win32 system therefore it could change with any Windows release. However, I think it’s probably a safe bet to rely on it given the number of applications in the field that already do. Without further ado, some code to get the size of the task bar.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;user32.dll&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr FindWindow<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> lpClassName, <span style="color: #6666cc; font-weight: bold;">string</span> lpWindowName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
APPBARDATA appBar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> APPBARDATA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">hWnd</span> <span style="color: #008000;">=</span> FindWindow<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Shell_TrayWnd&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">cbSize</span> <span style="color: #008000;">=</span> Marshal<span style="color: #008000;">.</span><span style="color: #008000;">SizeOf</span><span style="color: #008000;">&#40;</span>appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IntPtr</span> ret <span style="color: #008000;">=</span> SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg<span style="color: #008000;">.</span><span style="color: #0000FF;">ABM_GETTASKBARPOS</span>, <span style="color: #0600FF; font-weight: bold;">ref</span> appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Size s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Size<span style="color: #008000;">&#40;</span>appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span> appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">left</span>, appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">bottom</span> <span style="color: #008000;">-</span> appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">top</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Simple right?</p>
<h2>Modifying the Taskbar</h2>
<p>Remember earlier I said the system taskbar is not quite like a normal appbar? Well it’s special in that you can’t really change any of its properties like its size or position. This makes sense as you wouldn’t just want any program you install to play with the users taskbar; it’s sort of like an invasion of privacy. I’ve seen claims around the Internet that this can be pulled off in application code, which may be true prior to Vista; however I’ve tried all kinds of tricks based on SHAppBarMessage and can’t change the taskbar properties under Vista. Do you know how this can be done or if it’s even possible? I have found that you can change the task bar state. That is, you can toggle between &#8220;autohide&#8221; mode and &#8220;always on top&#8221; mode.</p>
<h2>Example Taskbar Code</h2>
<p>So, here is a little class I’ve put together to wrap the SHAppBarMessage functionality. I really haven&#8217;t paid attention to error handling or anything with it so if you use this you would need to address that.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Runtime.InteropServices</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Drawing</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> TaskbarInfoExample
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Provides methods for obtaining and modifying information for the system taskbar.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #6666cc; font-weight: bold;">class</span> TaskBar
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080;">#region Native API</span>
        <span style="color: #008080; font-style: italic;">// The native API functions/enums/structs needed to access taskbar info</span>
        <span style="color: #008080; font-style: italic;">// consult MSDN for more detailed information about them</span>
        <span style="color: #008000;">&#91;</span>StructLayout<span style="color: #008000;">&#40;</span>LayoutKind<span style="color: #008000;">.</span><span style="color: #0000FF;">Sequential</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">struct</span> RECT
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> left<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> top<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> right<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> bottom<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>StructLayout<span style="color: #008000;">&#40;</span>LayoutKind<span style="color: #008000;">.</span><span style="color: #0000FF;">Sequential</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">struct</span> APPBARDATA
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> Int32 cbSize<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> IntPtr hWnd<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> Int32 uCallbackMessage<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> ABEdge uEdge<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> RECT rc<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">public</span> IntPtr lParam<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABMsg
        <span style="color: #008000;">&#123;</span>
            ABM_NEW <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABM_REMOVE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABM_QUERYPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABM_SETPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
            ABM_GETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>,
            ABM_GETTASKBARPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>,
            ABM_ACTIVATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">6</span>,
            ABM_GETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span>,
            ABM_SETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">8</span>,
            ABM_WINDOWPOSCHANGED <span style="color: #008000;">=</span> <span style="color: #FF0000;">9</span>,
            ABM_SETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABEdge
        <span style="color: #008000;">&#123;</span>
            ABE_LEFT <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABE_TOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABE_RIGHT <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABE_BOTTOM <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">enum</span> ABState
        <span style="color: #008000;">&#123;</span>
            ABS_MANUAL <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABS_AUTOHIDE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABS_ALWAYSONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABS_AUTOHIDEANDONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;shell32.dll&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg dwMessage, <span style="color: #008000;">&#91;</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">ref</span> APPBARDATA pData<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;user32.dll&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr FindWindow<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> lpClassName, <span style="color: #6666cc; font-weight: bold;">string</span> lpWindowName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Represents the edge of the screen the task bar is docked to.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> TaskBarEdge
        <span style="color: #008000;">&#123;</span>
            Left <span style="color: #008000;">=</span> ABEdge<span style="color: #008000;">.</span><span style="color: #0000FF;">ABE_LEFT</span>,
            Top <span style="color: #008000;">=</span> ABEdge<span style="color: #008000;">.</span><span style="color: #0000FF;">ABE_TOP</span>,
            Right <span style="color: #008000;">=</span> ABEdge<span style="color: #008000;">.</span><span style="color: #0000FF;">ABE_RIGHT</span>,
            Bottom <span style="color: #008000;">=</span> ABEdge<span style="color: #008000;">.</span><span style="color: #0000FF;">ABE_BOTTOM</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The states the task bar can be in.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008000;">&#91;</span>Flags<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> TaskBarState
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// No autohide, not always top</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            None <span style="color: #008000;">=</span> ABState<span style="color: #008000;">.</span><span style="color: #0000FF;">ABS_MANUAL</span>,
&nbsp;
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// Hides task bar when mouse exits task bar region</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            AutoHide <span style="color: #008000;">=</span> ABState<span style="color: #008000;">.</span><span style="color: #0000FF;">ABS_AUTOHIDE</span>,
&nbsp;
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// Taskbar is always on top of other windows</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            AlwaysTop <span style="color: #008000;">=</span> ABState<span style="color: #008000;">.</span><span style="color: #0000FF;">ABS_ALWAYSONTOP</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the location, in screen coordinates of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The taskbar location.&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> Point GetTaskBarLocation<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> Point<span style="color: #008000;">&#40;</span>appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">left</span>, appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">top</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the size, in pixels of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The taskbar size.&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> Size GetTaskBarSize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> Size<span style="color: #008000;">&#40;</span>appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span> appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">left</span>, appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">bottom</span> <span style="color: #008000;">-</span> appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">rc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">top</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the edge of the screen that the task bar is docked to.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> TaskBarEdge GetTaskBarEdge<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>TaskBarEdge<span style="color: #008000;">&#41;</span>appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">uEdge</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the current state of the taskbar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> TaskBarState GetTaskBarState<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>TaskBarState<span style="color: #008000;">&#41;</span>SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg<span style="color: #008000;">.</span><span style="color: #0000FF;">ABM_GETSTATE</span>, <span style="color: #0600FF; font-weight: bold;">ref</span> appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Sets the state of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;state&quot;&gt;The new state.&lt;/param&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> SetTaskBarState<span style="color: #008000;">&#40;</span>TaskBarState state<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">lParam</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>IntPtr<span style="color: #008000;">&#41;</span>state<span style="color: #008000;">;</span>
&nbsp;
            SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg<span style="color: #008000;">.</span><span style="color: #0000FF;">ABM_SETSTATE</span>, <span style="color: #0600FF; font-weight: bold;">ref</span> appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets an APPBARDATA struct with valid location,size,and edge of the taskbar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> APPBARDATA GetTaskBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IntPtr</span> ret <span style="color: #008000;">=</span> SHAppBarMessage<span style="color: #008000;">&#40;</span>ABMsg<span style="color: #008000;">.</span><span style="color: #0000FF;">ABM_GETTASKBARPOS</span>, <span style="color: #0600FF; font-weight: bold;">ref</span> appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> appBar<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Creats an APPBARDATA struct with its hWnd member set to the task bar window.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> APPBARDATA CreateAppBarData<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> APPBARDATA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">hWnd</span> <span style="color: #008000;">=</span> FindWindow<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Shell_TrayWnd&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            appBar<span style="color: #008000;">.</span><span style="color: #0000FF;">cbSize</span> <span style="color: #008000;">=</span> Marshal<span style="color: #008000;">.</span><span style="color: #008000;">SizeOf</span><span style="color: #008000;">&#40;</span>appBar<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> appBar<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3>That’s All!</h3>
<p>That’s all I’ve got for now. I have included a little demo app you can download to demonstrate the class. You can find that <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/05/taskbarinfoexample.zip">here </a>Basically it just allows you to modify the task bar state and shows you all of its properties.</p>
<p>Hope you found this useful and saved yourself some time!</p>
<fb:like href='http://www.crowsprogramming.com/archives/88' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/88/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Launching and Viewing Processes in C#</title>
		<link>http://www.crowsprogramming.com/archives/83</link>
		<comments>http://www.crowsprogramming.com/archives/83#comments</comments>
		<pubDate>Wed, 15 Apr 2009 05:23:19 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=83</guid>
		<description><![CDATA[You can launch a new process from a C# application by using the Process class located in the System.Diagnostics namespace. The Process class also allows you to obtain a collection of all running processes on the system. How to Launch a New Process Starting a process is really easy. Process.Start&#40; &#34;Notepad.exe&#34; &#41;; And that’s it. [...]]]></description>
			<content:encoded><![CDATA[<p>You can launch a new process from a C# application by using the Process class located in the System.Diagnostics namespace. The Process class also allows you to obtain a collection of all running processes on the system.</p>
<h2>How to Launch a New Process</h2>
<p>Starting a process is really easy.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Notepad.exe&quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And that’s it. If Notepad.exe exists on your system then it will start. Make sure that if you do not specify a complete path then the name you do present is available in your environment path. You can wait for the newly created process to terminate as well.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process p <span style="color: #008000;">=</span> Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Notepad.exe&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
p<span style="color: #008000;">.</span><span style="color: #0000FF;">WaitForExit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Keep in mind that WaitForExit will block the calling thread. If you don’t want that behavior considering launching the new process on a thread of its own. You can also use the ProcessStartInfo class to pass information to the Start method. This example launches the new process on a thread from the thread pool via an anonymous method. Remember to include System.Threading.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// launch the program / process on a new thread from the thread pool</span>
ThreadPool<span style="color: #008000;">.</span><span style="color: #0000FF;">QueueUserWorkItem</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">&#40;</span>WaitCallback<span style="color: #008000;">&#41;</span><span style="color: #6666cc; font-weight: bold;">delegate</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> state<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Notepad.exe&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Process p <span style="color: #008000;">=</span> Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span>psi<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    p<span style="color: #008000;">.</span><span style="color: #0000FF;">WaitForExit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Passing Arguments to the New Process</h2>
<p>You can also pass arguments to a new process. The next example will launch Notepad and tell it to open the file MyFile.txt.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Notepad.exe&quot;</span>, <span style="color: #666666;">@&quot;C:\My\Path\MyFile.txt&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Process p <span style="color: #008000;">=</span> Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span>psi<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2> Launching a Document and Setting the Verb</h2>
<p>There are some other interesting things you can do with the Process class. For instance, instead of specifying a file name in Process.Start like we did above with Notepad.exe, we could specify a file or document. The method would then open that file with the registered default application for that type of file. You can also specify a verb that is associated with that file type. A verb represents an action that is associated with that file type. So, if I wanted to launch the default application for a .txt file and have that file printed I could do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;C:\My\Path\MyFile.txt&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
psi<span style="color: #008000;">.</span><span style="color: #0000FF;">Verb</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;print&quot;</span><span style="color: #008000;">;</span>
&nbsp;
Process p <span style="color: #008000;">=</span> Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span>psi<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
p<span style="color: #008000;">.</span><span style="color: #0000FF;">WaitForExit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Listing All Running Processes</h2>
<p>The last thing I want to show you is how easy it is to view a list of all processes running on the system with C#. Assuming you have a ListBox name listbox1, the following code fragment would add an entry to the ListBox with the name of each process running on the system.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> processes <span style="color: #008000;">=</span> Process<span style="color: #008000;">.</span><span style="color: #0000FF;">GetProcesses</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span> Process process <span style="color: #0600FF; font-weight: bold;">in</span> processes <span style="color: #008000;">&#41;</span>
   listBox1<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span> process<span style="color: #008000;">.</span><span style="color: #0000FF;">ProcessName</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Well, that’s it for today. Hope this information comes in handy for some of you!</p>
<fb:like href='http://www.crowsprogramming.com/archives/83' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/83/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How To Get Screen Shot Capture in C#</title>
		<link>http://www.crowsprogramming.com/archives/78</link>
		<comments>http://www.crowsprogramming.com/archives/78#comments</comments>
		<pubDate>Mon, 13 Apr 2009 06:36:10 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=78</guid>
		<description><![CDATA[It’s often necessary to programmatically get a screen shot of the desktop and save it to a file. This is pretty easy with C#; we can create a simple method that will save an image of whatever is on the screen or desktop. Saving a Bitmap Image of the Screen First make sure you include [...]]]></description>
			<content:encoded><![CDATA[<p>It’s often necessary to programmatically get a screen shot of the desktop and save it to a file. This is pretty easy with C#; we can create a simple method that will save an image of whatever is on the screen or desktop.</p>
<h2>Saving a Bitmap Image of the Screen</h2>
<p>First make sure you include the System.Drawing.Imaging namespace. Now, all we really have to do is create a new bitmap and use the CopyFromScreen method of the bitmaps Graphics device.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a screen capture in the specified image format to a file.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> SaveScreenShot<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename, ImageFormat format<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
        Bitmap screenShot <span style="color: #008000;">=</span> CaptureScreenShot<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  	screenShot<span style="color: #008000;">.</span><span style="color: #0000FF;">Save</span><span style="color: #008000;">&#40;</span>filename, format<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a picture of the screen to a bitmap image.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The saved bitmap.&lt;/returns&gt;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> Bitmap CaptureScreenShot<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
 	<span style="color: #008080; font-style: italic;">// get the bounding area of the screen containing (0,0)</span>
        <span style="color: #008080; font-style: italic;">// remember in a multidisplay environment you don't know which display holds this point</span>
    	Rectangle bounds <span style="color: #008000;">=</span> Screen<span style="color: #008000;">.</span><span style="color: #0000FF;">GetBounds</span><span style="color: #008000;">&#40;</span>Point<span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	<span style="color: #008080; font-style: italic;">// create the bitmap to copy the screen shot to</span>
   	Bitmap bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Bitmap<span style="color: #008000;">&#40;</span>bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Width</span>, bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Height</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	<span style="color: #008080; font-style: italic;">// now copy the screen image to the graphics device from the bitmap</span>
   	<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>Graphics gr <span style="color: #008000;">=</span> Graphics<span style="color: #008000;">.</span><span style="color: #0000FF;">FromImage</span><span style="color: #008000;">&#40;</span>bitmap<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
   	<span style="color: #008000;">&#123;</span>
       	   gr<span style="color: #008000;">.</span><span style="color: #0000FF;">CopyFromScreen</span><span style="color: #008000;">&#40;</span>Point<span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span>, Point<span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span>, bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Size</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   	<span style="color: #008000;">&#125;</span>
&nbsp;
  	<span style="color: #0600FF; font-weight: bold;">return</span> bitmap<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>And that’s really all there is to capturing a screen shot. You can save it to whatever file you would like and in any of the image formats supported by ImageFormat such as PNG or JPEG. Keep in mind if your working in a multidisplay environment you’ll want to be careful which display your targeting. Or perhaps you may want a huge image of all the desktop displays.</p>
<p>You can use the above code simply by calling the SaveScreenShot method with a file name and image format to save to:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//save screen shot in PNG image format</span>
SaveScreenShot<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyScreenShot.png&quot;</span>, ImageFormat<span style="color: #008000;">.</span><span style="color: #0000FF;">Png</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>With a really small change you can modify the above code to save a screen shot of an arbitrary control instead of the entire desktop display.</p>
<h2>Saving a Screen Capture of a Control</h2>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a screen capture of the specified control to a file.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;control&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> SaveControlShot<span style="color: #008000;">&#40;</span>Control control, <span style="color: #6666cc; font-weight: bold;">string</span> filename, ImageFormat format<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   	Bitmap controlShot <span style="color: #008000;">=</span> CaptureControlShot<span style="color: #008000;">&#40;</span>control<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   	controlShot<span style="color: #008000;">.</span><span style="color: #0000FF;">Save</span><span style="color: #008000;">&#40;</span>filename, format<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Gets a bitmap image of the specified control.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;control&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> Bitmap CaptureControlShot<span style="color: #008000;">&#40;</span>Control control<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// get control bounding rectangle</span>
     	Rectangle bounds <span style="color: #008000;">=</span> control<span style="color: #008000;">.</span><span style="color: #0000FF;">Bounds</span><span style="color: #008000;">;</span>
&nbsp;
   	<span style="color: #008080; font-style: italic;">// create the new bitmap that holds the image of the control</span>
     	Bitmap bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Bitmap<span style="color: #008000;">&#40;</span>bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Width</span>, bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Height</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   	<span style="color: #008080; font-style: italic;">// copy controls image data to the bitmaps graphics device</span>
    	<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>Graphics gr <span style="color: #008000;">=</span> Graphics<span style="color: #008000;">.</span><span style="color: #0000FF;">FromImage</span><span style="color: #008000;">&#40;</span>bitmap<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    	<span style="color: #008000;">&#123;</span>
        	gr<span style="color: #008000;">.</span><span style="color: #0000FF;">CopyFromScreen</span><span style="color: #008000;">&#40;</span>control<span style="color: #008000;">.</span><span style="color: #0000FF;">Location</span>, Point<span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span>, bounds<span style="color: #008000;">.</span><span style="color: #0000FF;">Size</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     	<span style="color: #008000;">&#125;</span>
&nbsp;
    	<span style="color: #0600FF; font-weight: bold;">return</span> bitmap<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>And you can use this just as easily as the previous screen capture method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// if &quot;this&quot; is a control, like a form</span>
SaveControlShot<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <span style="color: #666666;">&quot;MyControlShot.png&quot;</span>, ImageFormat<span style="color: #008000;">.</span><span style="color: #0000FF;">Png</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And there you have it, an example of simple methods for saving a screen shot or an image of a control. I Hope you find this helpful.  </p>
<fb:like href='http://www.crowsprogramming.com/archives/78' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/78/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Introduction to Multithreading in C#</title>
		<link>http://www.crowsprogramming.com/archives/71</link>
		<comments>http://www.crowsprogramming.com/archives/71#comments</comments>
		<pubDate>Thu, 09 Apr 2009 00:34:18 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=71</guid>
		<description><![CDATA[This article is a very basic introductory tutorial for using multiple threads in C#. I’ll explain what threads are, why you would want to use them, and how to use them. I’ll also show you several examples for creating threads, killing threads, etc. What’s a Thread? A computer program is generally very linear. That is, [...]]]></description>
			<content:encoded><![CDATA[<p>This article is a very basic introductory tutorial for using multiple threads in C#. I’ll explain what threads are, why you would want to use them, and how to use them. I’ll also show you several examples for creating threads, killing threads, etc.</p>
<h2>What’s a Thread?</h2>
<p>A computer program is generally very linear. That is, you have a sequence of instructions that get executed one after another in an orderly and predictable fashion. This scenario only affords you one path of execution. Threads allow you to execute multiple paths of code simultaneously. Now, <i>simultaneously</i> in this case does not necessarily mean <i>physically</i> at the same time. Both your operating system and processor must support this for that to be true. Threads are not particular to C#; most modern programming languages such as Visual Basic.Net support the concept of threads.</p>
<h2>So Why Do I Need Multiple Threads?</h2>
<p>Threading is handy because many programming tasks are asynchronous. That is, I can start the task and go on about my business and when that task is finished it can let me know and I can take action. An example of this would be downloading files from a remote location. I can start downloading three files and when the first is finished I can process it while the others continue to download.</p>
<p>There are numerous other reasons. Consider for instance a long task like sorting a million numbers. If I start that task on the thread that runs the GUI then I couldn’t update my user interface which means I couldn’t respond to user requests like button clicks.</p>
<p>Ok, lets move on to an example of creating a new thread via C#.</p>
<h2>Creating a Thread with C#</h2>
<p>Creating a thread is easy; we make use of the Thread object from the System.Threading namespace. When we create the thread we must pass it a ParameterizedThreadStart  or ThreadStart delegate. This will be the method that gets invoked on the new thread – it’s the starting point. New threads begin life in a stopped state. To make it run we call the Thread.Start method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span>MyThreadFunction<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
myThread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> MyThreadFunction<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;HI&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Congratulations, you’ve created your first thread that runs in parallel with your main thread.</p>
<h2> Passing an Argument to the New Thread</h2>
<p>You can easily pass an argument to the thread like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span>MyThreadFunction<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
myThread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;HELLO WORLD&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> MyThreadFunction<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> x<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>x <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Keep in mind that this is not the best way to pass data to the thread. Since Thread.Start accepts only an object this is not very type safe. Image if we didn’t pass a string or the object didn’t have a ToString method. The best way to accomplish this would be to encapsulate your thread function in a class with data members you could set ahead of time.</p>
<h2> Waiting for a Thread to Stop</h2>
<p>Now that we have our thread up and running, we may at some point wish to wait for it to complete. This is accomplished with the Thread.Join method. Here is an example for Thread.Join:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span>MyThreadFunction<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
myThread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;HELLO WORLD&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
myThread<span style="color: #008000;">.</span><span style="color: #0000FF;">Join</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ALL DONE!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//-elsewhere</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> MyThreadFunction<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> x<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>x <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>When the first piece of code executes it will create a new thread that will begin running in MyThreadFunction. After calling myThread.join that thread will go to sleep and stop executing until MyThreadFunction returns. This will happen after you dismiss the message box. Finally, when MyThreadFunction exits and the thread is destroyed, the original thread will continue execution at the next statement and pop its message box.</p>
<p>One thing to watch out for is what happens if the thread function never returns meaning the thread never dies. In this situation you can specify a timeout value in Thread.Join. The method will block for a predetermined amount of time waiting for the thread to terminate. If the thread did not terminate then Thread.Join would return false.</p>
<h2>Stopping a Thread</h2>
<p>Stopping a thread is simple. You call Thread.Abort on the thread you wish to stop.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">myThread<span style="color: #008000;">.</span><span style="color: #0000FF;">Abort</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This will cause a ThreadAbortException to be raised on the thread you are trying to stop. Now this <i>usually</i> stops the thread. It’s possible that the thread can abort your abort and continue living. There are a few other circumstances that can prevent the thread from aborting.</p>
<h2>Sharing Variables</h2>
<p>When you have two or more threading running it’s possible that they could be executing at the same time. This can create problems when both threads are trying to read/write to the same variable. You have to synchronize thread access to shared variables. There are many synchronization primitives available to you in C# via the .Net Framework Library such as AutoResetEvent, Monitor, and Mutex. This is a big subject so I will defer it till another post.</p>
<p>Along those same lines here’s a tip: If you create secondary threads they cannot modify controls on your GUI. Only the thread that created a control can modify its properties. You will generate the dreaded <i>illegal cross thread exception</i>. <a href="http://www.crowsprogramming.com/archives/18">I’ve already posted a brief work around for this problem</a></p>
<p>So that’s it for my C# threading tutorial. Now you know the basics of how to create a thread, how to kill a thread, how to wait for a thread, and some general threading principles. This is a big subject and I’ve hardly done it justice with this little bit of writing. If there are sufficient interests, I will elaborate on some more advance multithreading techniques that are applicable in all .Net languages – not just C#. I’ll leave you with a small incomplete pro and con list about using multiple threads.</p>
<h3>Advantages of Multithreading</h3>
<ul>
<li> Improved performance – Multiple threads can execute concurrently.</li>
<li> Streamline application logic – Some tasks are easier to conceptualize this way</li>
<li> Improves responsiveness of an application – GUI still works under heavy load.</li>
</ul>
<p></p>
<h3>Disadvantages of Multithreading</h3>
<ul>
<li> Hard to write and debug – Nuff said!!</li>
<li> Performance impact from synchronizing access to shared variables</li>
<li> There is a limit to how many threads an operating system can handle efficiently</li>
<li> Context switching between threads can hurt performance</li>
</ul>
<fb:like href='http://www.crowsprogramming.com/archives/71' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/71/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Playing an MP3 or WAV File in C#</title>
		<link>http://www.crowsprogramming.com/archives/58</link>
		<comments>http://www.crowsprogramming.com/archives/58#comments</comments>
		<pubDate>Sun, 05 Apr 2009 05:43:20 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=58</guid>
		<description><![CDATA[Playing an audio file such as an MP3 or WAV is incredibly easy in C#. For WAV files you can use the SoundPlayer class found in the System.Media namespace. Playing an MP3 will require referencing the Windows Media Player COM component. How to Play a WAV file To play the WAV file simply create a [...]]]></description>
			<content:encoded><![CDATA[<p>Playing an audio file such as an MP3 or WAV is incredibly easy in C#. For WAV files you can use the SoundPlayer class found in the System.Media namespace. Playing an MP3 will require referencing the Windows Media Player COM component.</p>
<p></p>
<h2>How to Play a WAV file</h2>
<p>To play the WAV file simply create a new SoundPlayer object, set the SoundLocation property to the location of your WAV file, and then use the Play method to play it.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Media</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SoundPlayer</span> player <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Media</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SoundPlayer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
player<span style="color: #008000;">.</span><span style="color: #0000FF;">SoundLocation</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;My Wav File.wav&quot;</span><span style="color: #008000;">;</span>
player<span style="color: #008000;">.</span><span style="color: #0000FF;">Play</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p></p>
<h2>How to Play an MP3 file</h2>
<p>Playing an MP3 with C# is just as easy as playing a WAV except that it requires you to use the Window Media Player COM component. So first, add a reference to wmp.dll, which you can find in the System32 directory. Here is an example of how to play an MP3 file:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">WMPLib<span style="color: #008000;">.</span><span style="color: #0000FF;">WindowsMediaPlayer</span> wplayer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WMPLib<span style="color: #008000;">.</span><span style="color: #0000FF;">WindowsMediaPlayer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
wplayer<span style="color: #008000;">.</span><span style="color: #0000FF;">URL</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;My MP3 file.mp3&quot;</span><span style="color: #008000;">;</span>
wplayer<span style="color: #008000;">.</span><span style="color: #0000FF;">controls</span><span style="color: #008000;">.</span><span style="color: #0000FF;">play</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>So there you have it; a simple example of how to play an MP3 and WAV file using C#. I hope you find it useful. If you have any questions feel free to ask.</p>
<fb:like href='http://www.crowsprogramming.com/archives/58' send='false' layout='standard' show_faces='true' width='450' height='65' action='like' colorscheme='light' font='lucida+grande'></fb:like>]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/58/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

