Showing posts with label C# Programming. Show all posts
Showing posts with label C# Programming. Show all posts

Thursday, June 4, 2009

Reposition a console window in C#

Motivation

When writing demo code I think a very nice interface is a console application. It is quick way of getting an application to input and output data without having to think on all those complex UI problems.

When you have to console projects, eg. client and server, the windows will most likely start cascaded. You then have to move one of them to be able to read stuff in both at the same time. This is really annoying.

How to

First you will need to get some native APIs:

   1: public struct RECT
   2: {
   3:    public int left;
   4:    public int top;
   5:    public int right;
   6:    public int bottom;
   7: }
   8:  
   9: public static class NativeMethods
  10: {
  11:    public const UInt32 WM_MOVE = 0x0003;
  12:  
  13:    [DllImport("kernel32.dll")]
  14:    public static extern IntPtr GetConsoleWindow();
  15:  
  16:    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
  17:    public static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);
  18:  
  19:    /// <summary>
  20:    /// The MoveWindow function changes the position and dimensions of the specified window. For a top-level window, the position and dimensions are relative to the upper-left corner of the screen. For a child window, they are relative to the upper-left corner of the parent window's client area.
  21:    /// </summary>
  22:    /// <param name="hWnd">Handle to the window.</param>
  23:    /// <param name="X">Specifies the new position of the left side of the window.</param>
  24:    /// <param name="Y">Specifies the new position of the top of the window.</param>
  25:    /// <param name="nWidth">Specifies the new width of the window.</param>
  26:    /// <param name="nHeight">Specifies the new height of the window.</param>
  27:    /// <param name="bRepaint">Specifies whether the window is to be repainted. If this parameter is TRUE, the window receives a message. If the parameter is FALSE, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of moving a child window.</param>
  28:    /// <returns>If the function succeeds, the return value is nonzero.
  29:    /// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para></returns>
  30:    [DllImport("user32.dll", SetLastError = true)]
  31:    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  32:  
  33:    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
  34:    public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);
  35: }

First you use the GetConsoleWindow API to get a handle to the window where the console buffers are being outputted.

The second step is to get the RECT structure populated with the window rectangle coordinates. We need this to compute the width and height of the window because we don’t want to change that and those are needed for the next API call.

The third and final step is calling MoveWindow API passing in the new origin and the same dimensions. Where goes a method that does just that:

   1: public static void RePositionWindow(int x, int y)
   2: {
   3:     IntPtr windowHandle = NativeMethods.GetConsoleWindow();
   4:     RECT rect = new RECT();
   5:     NativeMethods.GetWindowRect(windowHandle, ref rect);
   6:     NativeMethods.MoveWindow(windowHandle, x, y, rect.right - rect.left, rect.bottom - rect.top, true);
   7: }

I call this in the Main method before doing anything:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         ConsoleUtils.RePositionWindow(800, 100);
   6:  
   7:         // add code bellow
   8:     }
   9: }

I give each window a hardcoded position but you can try a more elaborate algorithm like dividing the available desktop space.

Monday, September 1, 2008

Subtleties in C# Anonymous methods

Last Friday I had a really bad time figuring out a bug in an anonymous method. The bug was related with the way anonymous methods are implemented in C# and variable scoping. Being the scenes the compiler is generating a class to hold the delegate and references to the variables that are grabbed in the scope of the block holding the delegate. The reference will be hold in memory for the all lifecycle of the delegate object.

The original code was:

foreach (PropertyInfo property in allProperties)
{
    object propertyValue = GetTypePropertyValue(this, property);

    MyObject1 myObject1Value = propertyValue as INotifyPropertyChanged;
    if (myObject1Value != null)
    {
        myObject1Value.PropertyChanged += delegate(object sender, PropertyChangedEventArgs ev)
        {
            this.NotifyPropertyChanged(property.Name);
        };
    }
}
The code fixed code is something like this:
foreach (PropertyInfo property in allProperties)
{
    object propertyValue = GetTypePropertyValue(this, property);

    MyObject1 myObject1Value = propertyValue as INotifyPropertyChanged;
    if (myObject1Value != null)
    {
        string propertyName = property.Name;
        myObject1Value.PropertyChanged += delegate(object sender, PropertyChangedEventArgs ev)
        {
            this.NotifyPropertyChanged(propertyName);
        };
    }
}

The difference is declaring a string variable outside the anonymous method and copying the property’s name into it. Being the scene the compiler will grab a reference to the string that is an immutable object and that reference won’t get modified.

Friday, August 29, 2008

Quick InternalsVisibleTo How-to

The InternalsVisibleToAttribute allows an assembly to make its members marked with the internal visibility modifier visible to other assemblies. I’m not going to discuss whether this is good or bad, as every thing in life its not black or white, its rather gray :).

When the project assemblies are not strongly signed then it is just putting the assembly name without the version, culture and public key token, typically in the “assemblyinfo.cs” file.

[assembly: InternalsVisiblieTo(“MyCompany.MyAssemblyName”)]

When the project assemblies are strongly sign then the first step is getting the public key of the assembly that is going to see the internals. To do this we use the SN command.

sn –Tp <assembly file name>

This will print out the huge public key of the assembly. The it is just adding it to the attribute:

[assembly: InternalsVisibleTo(“MyCompany.MyAssemblyName, PublicKey= 02f…f0c68e6c7”)]

(I shorted the key because it is a huge string).