<?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>Bitmatic &#187; native code</title>
	<atom:link href="http://bitmatic.com/tag/native-code/feed" rel="self" type="application/rss+xml" />
	<link>http://bitmatic.com</link>
	<description>Lean IT-solutions in .NET/C#</description>
	<lastBuildDate>Tue, 11 Jan 2011 09:37:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Redirecting MouseWheel events to another control</title>
		<link>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control</link>
		<comments>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control#comments</comments>
		<pubDate>Sun, 01 Nov 2009 12:42:36 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[native code]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=478</guid>
		<description><![CDATA[Redirecting events from one control to another is quite easy. I recently needed it for an application that uses a number of ComboBoxes to filter data in a DataGridView. It was very confusing to the user when she selected an item in the ComboBox and subsequently tried using the mouse wheel to scroll through the [...]]]></description>
			<content:encoded><![CDATA[<p>Redirecting events from one control to another is quite easy. I recently needed it for an application that uses a number of ComboBoxes to filter data in a DataGridView. It was very confusing to the user when she selected an item in the ComboBox and subsequently tried using the mouse wheel to scroll through the data, that it would be the ComboBox, and not the DataGridView that would be scrolling.<br />
I decided to make a special ComboBox that would redirect Mouse wheel events to the DataGridView, instead of trying to fix it by manipulating focus. Manipulating focus gives you nothing but problems in my experience.</p>
<h3>The ComboBox with MouseWheel redirect</h3>
<p>The class i implemented for this solution just overrides the WndProc function, which handles all the messages sent to the control. It then reroutes mouse wheel events to another control (the reciever) through the Win32 API function SendMessage.<br />
That&#8217;s it&#8230;<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> ComboBoxMWRedirect : ComboBox
{
    [DllImport(<span class="str">"user32.dll"</span>, CharSet = CharSet.Auto)]
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr SendMessage(
        IntPtr hWnd,
        <span class="kwrd">int</span> message,
        IntPtr WParam,
        IntPtr LParam);

    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> WM_MOUSEWHEEL = 0x020A;
    <span class="kwrd">private</span> Control _reciever;

    <span class="rem">//needed for designer support</span>
    <span class="kwrd">private</span> ComboBoxMWRedirect() {}

    <span class="kwrd">public</span> ComboBoxMWRedirect(Control reciever)
    {
        _reciever = reciever;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> WndProc(<span class="kwrd">ref</span> Message message)
    {
        <span class="kwrd">if</span> (message.Msg == WM_MOUSEWHEEL)
        {
            <span class="rem">//route mouse wheel messages to the reciever</span>
            SendMessage(
                _reciever.Handle,
                message.Msg,
                message.WParam,
                message.LParam);
        }
        <span class="kwrd">else</span>
        {
            <span class="rem">//route all other messages on to the base class</span>
            <span class="kwrd">base</span>.WndProc(<span class="kwrd">ref</span> message);
        }
    }
}</pre>
<p>Now to have one of your ComboBoxes redirect the mouse wheel, just use one of these instead, and specify the recieving control when you call the constructor. If, for instance, i want to redirect to a DataGridView calle dataGridView1 i would construct the redirecting ComboBox like this:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
ComboBoxMWRedirect cb = <span class="kwrd">new</span> ComboBoxMWRedirect(dataGridView1);</pre>
<h3>Completely avoiding the event</h3>
<p>The code can also be used to avoid the Mouse wheel event altogether. Just change the WndProc overridde to the code below, and mouse wheel events will be ignored.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> WndProc(<span class="kwrd">ref</span> Message message)
{
    <span class="rem">//avoid mouse wheel events</span>
    <span class="kwrd">if</span> (message.Msg != WM_MOUSEWHEEL)
        <span class="kwrd">base</span>.WndProc(<span class="kwrd">ref</span> message);
}</pre>
<p>Overriding WndProc gives you a lot of power and control over what happens in your application. This particular (very limited) example handles MouseWheel events on a ComboBox, but you can really use this to do a lot of very powerful stuff, like disabling the keyboard or parts of it, routing messages to other controls, broadcasting messages to have several controls react to the same message, etc. etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Single instance applications in Windows CE</title>
		<link>http://bitmatic.com/c/single-instance-applications-in-windows-ce</link>
		<comments>http://bitmatic.com/c/single-instance-applications-in-windows-ce#comments</comments>
		<pubDate>Mon, 13 Jul 2009 18:22:36 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[native code]]></category>
		<category><![CDATA[Windows CE]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=370</guid>
		<description><![CDATA[I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself. I was a bit surprised that there is [...]]]></description>
			<content:encoded><![CDATA[<p>I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself.<br />
I was a bit surprised that there is no easy way of accomplishing this. Searching the internet gave me basically no easy answer either, but there seems to be 3 standard ways of accomplishing this.</p>
<ul>
<li>Write a dummy text file on startup, and check the existance of this file.</li>
<li>Write to a registry-key on startup, and use that as a &#8220;mutex&#8221;.</li>
<li>Use a named mutex with a system-wide scope.</li>
</ul>
<p>Obviously the first two have the problem that they may break the program, if the program exits without resetting the file/registry-key used as a pseudo-mutex. They are also very crude and not very elegant&#8230;. But that&#8217;s up to personal taste i guess.<br />
I went for the third choice; The named mutex.</p>
<h3>The named mutex in Windows CE</h3>
<p>The .NET Compact Framework does not support named mutexes. Luckily Windows CE does however, and it can be imported through a few functions in coredll.dll.<br />
A named mutex is an object created by the OS with a name specified on creation. The actual functionality of the object is not very interesting right now. The interesting bit is that only one object can exist with any given name. If you try to create another object with the same name, you get an error.<br />
Basically, if you create a named mutex with the name of the application itself, this can be used to ensure that only one instance of the application can be run.</p>
<h3>Wrapping it up</h3>
<p>I decided to wrap it all up nicely in a class, so that it will be easy to use. The class is called SingleInstanceApplication, and here is what i came up with:</p>
<pre class="csharpcode">
<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> System.Runtime.InteropServices;
<span class="kwrd">using</span> System.Reflection;

<span class="kwrd">namespace</span> Bitmatic
{
  <span class="kwrd">static</span> <span class="kwrd">class</span> SingleInstanceApplication
  {
    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr CreateMutex(IntPtr Attr, <span class="kwrd">bool</span> Own, <span class="kwrd">string</span> Name);

    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">bool</span> ReleaseMutex(IntPtr hMutex);

    <span class="kwrd">const</span> <span class="kwrd">long</span> ERROR_ALREADY_EXISTS = 183;

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Run(Form frm)
    {
      <span class="kwrd">string</span> name = Assembly.GetExecutingAssembly().GetName().Name;
      IntPtr mutexHandle = CreateMutex(IntPtr.Zero, <span class="kwrd">true</span>, name);
      <span class="kwrd">long</span> error = Marshal.GetLastWin32Error();

      <span class="kwrd">if</span> (error != ERROR_ALREADY_EXISTS)
        Application.Run(frm);

      ReleaseMutex(mutexHandle);
    }
  }
}</pre>
<p>Feel free to steal&#8230;.<br />
The class imports the two native functions for creating and destroying mutexes, and has only a single public function.<br />
The Run function tries to create a mutex with the name of the application. It then checks the error code returned, to see if the mutex already exists, and if it doesn&#8217;t; starts the application. Finally it releases the mutex.<br />
Very simple, and quite a bit more elegant than the file/registry based solutions.</p>
<h3>Using it</h3>
<p>Using the class is very very simple. Just add the class itself to your project, open up Program.cs and replace:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  Application.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>with:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  SingleInstanceApplication.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>You only really changed one line, and now you have an application that is guaranteed to run  only as a single instance.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/single-instance-applications-in-windows-ce/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Implementing a scrolling RichTextBox</title>
		<link>http://bitmatic.com/c/implementing-a-scrolling-richtextbox</link>
		<comments>http://bitmatic.com/c/implementing-a-scrolling-richtextbox#comments</comments>
		<pubDate>Sun, 10 May 2009 16:45:17 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[native code]]></category>
		<category><![CDATA[Richtextbox]]></category>
		<category><![CDATA[Scroll]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=283</guid>
		<description><![CDATA[It is often necessary to make a .NET RichTextBox scroll to the top or the bottom. Unfotunately there is no direct method of doing this in the class itself. One possible solution involves using the ScrollToCaret() function of the control. This method is outlined in my first post about RichTextBox scrolling. It appears that some [...]]]></description>
			<content:encoded><![CDATA[<p>It is often necessary to make a .NET RichTextBox scroll to the top or the bottom. Unfotunately there is no direct method of doing this in the class itself.<br />
One possible solution involves using the ScrollToCaret() function of the control. This method is outlined in my <a href="http://bitmatic.com/csharp/scrolling-a-c-richtextbox-when-adding-text">first post about RichTextBox scrolling</a>. It appears that some programmers have had problems with that solution though. It requires careful management of focus in the application to work under all circumstances.</p>
<h3>The ScrollingRichTextBox</h3>
<p>A far more elegant solution is to use the underlying message system to control the scroll. Using the SendMessage function it is possible to send a <a href="http://msdn.microsoft.com/en-us/library/bb787577(VS.85).aspx">WM_VSCROLL</a> message to the control that makes the control scroll without needing to worry about focus.<br />
I think the best solution is to make a small class that inherits from RichTextBox, and neatly wraps the SendMessage calls necessary to make it work. Many programmers are unfamiliar with the syntax involved, so wrapping it in a more familiar syntax is a good idea.</p>
<p>The complete class looks like this:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">class</span> ScrollingRichTextBox : System.Windows.Forms.RichTextBox
{
  [DllImport(<span class="str">"user32.dll"</span>, CharSet = CharSet.Auto)]
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr SendMessage(
    IntPtr hWnd,
    <span class="kwrd">uint</span> Msg,
    IntPtr wParam,
    IntPtr lParam);

  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> WM_VSCROLL = 277;
  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> SB_LINEUP = 0;
  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> SB_LINEDOWN = 1;
  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> SB_TOP = 6;
  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> SB_BOTTOM = 7;

  <span class="kwrd">public</span> <span class="kwrd">void</span> ScrollToBottom()
  {
    SendMessage(Handle, WM_VSCROLL, <span class="kwrd">new</span> IntPtr(SB_BOTTOM), <span class="kwrd">new</span> IntPtr(0));
  }

  <span class="kwrd">public</span> <span class="kwrd">void</span> ScrollToTop()
  {
    SendMessage(Handle, WM_VSCROLL, <span class="kwrd">new</span> IntPtr(SB_TOP), <span class="kwrd">new</span> IntPtr(0));
  }

  <span class="kwrd">public</span> <span class="kwrd">void</span> ScrollLineDown()
  {
    SendMessage(Handle, WM_VSCROLL, <span class="kwrd">new</span> IntPtr(SB_LINEDOWN), <span class="kwrd">new</span> IntPtr(0));
  }

  <span class="kwrd">public</span> <span class="kwrd">void</span> ScrollLineUp()
  {
    SendMessage(Handle, WM_VSCROLL, <span class="kwrd">new</span> IntPtr(SB_LINEUP), <span class="kwrd">new</span> IntPtr(0));
  }
}</pre>
<p>Feel free to steal&#8230;</p>
<h3>How it works</h3>
<p>The class imports the SendMessage function from the user32.dll system library. I&#8217;m not gonna go deeply into that function in this post. It is insanely powerfull and deserves it&#8217;s own post someday. It allows the program to send native windows messages to the control. The message in play here is the <a href="http://msdn.microsoft.com/en-us/library/bb787577(VS.85).aspx">WM_VSCROLL</a> message that takes a parameter that tells it how to scroll. These parameters are constants that are defined in the <a href="http://doc.ddart.net/msdn/header/include/winuser.h.html">winuser.h</a> header file.</p>
<p>I have implemented four functions in this class, allowing it to scroll to the top and bottom, as well as a single line up and down.</p>
<p>With the SendMessage function imported and using <a href="http://doc.ddart.net/msdn/header/include/winuser.h.html">winuser.h</a> as a reference you could easily implement even more functionality in the class, such as pageup/pagedown (SB_PAGEUP/SB_PAGEDOWN), but i don&#8217;t want to bloat the class with that for this article. The principle is what counts here.</p>
<h3>A simple usage example</h3>
<p>For applications that require this sort of scrolling, using the ScrollingRichTextBox over the ordinary RichTextBox is the way to go. In <a href="http://bitmatic.com/csharp/scrolling-a-c-richtextbox-when-adding-text">a previous blog post</a>, i talked about hooking up to the OnTextChanged event of a RichTextBox and using ScrollToCaret() to do the scrolling. A method that has a few issues.<br />
Now, using the ScrollingRichTextBox, these issues are resolved and the complete code for that event looks like this:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">private</span> <span class="kwrd">void</span> scrollingRichTextBox_TextChanged(<span class="kwrd">object</span> sender, EventArgs e)
{
  scrollingRichTextBox.ScrollToBottom();
}</pre>
<p>Neat huh?</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/implementing-a-scrolling-richtextbox/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

