Click here to Skip to main content
15,860,972 members
Articles / Desktop Programming / Win32

Marshaling with C# – Chapter 3: Marshaling Compound Types

Rate me:
Please Sign up or sign in to vote.
4.92/5 (30 votes)
28 Dec 2010CPL20 min read 109.2K   56   15
Learn how to marshal compound types (structures, unions, etc.) in C#.
Download PDF and XPS versions of the book here.
Chapter 1: Introducing Marshaling 
Chapter 2: Marshaling Simple Types 
Chapter 3: Marshaling Compound Types  

Chapter Contents

Contents of this chapter:

  • Chapter Contents
  • Overview
  • Introduction
  • Marshaling Unmanaged Structures
    • How to Marshal a Structure
    • Handling Memory Layout Problem
    • Try It Out!
  • Marshaling Unions
    • A Short Speech About Unions
    • How to Marshal a Union
    • Unions with Arrays
    • Try It Out!
  • Value-Types and Reference-Types
  • Passing Mechanism
  • Real-World Examples
    • The DEVMODE Structure
    • Working with Display Settings
  • Summary

Overview

This chapter demonstrates how to marshal compound types. Compound types are those build of other types, for example structures and classes.

Like the previous chapter. This chapter breaks unmanaged compound types into two categories, structures and unions. We first discuss structures and then we will dive into unions and how to marshal them.

You might ask, why you have divided compound types into just two categories, structures and unions, I can create classes too? The answer is easy. For its simplicity, this book will focus primarily on Windows API. Therefore, you will find much of our talking about Win32 functions and structures. However, the same rules apply to classes and other unmanaged types.

Introduction

A compound type encapsulates related data together; it provides an organized and arranged container for transmitting a group of variables between the client application and the unmanaged server. It consists (usually) of variables of simple types and (optionally) other compound types. In addition, it could define other compound types inside.

Compound types come in two kinds:

  • Unmanaged Structures
  • Unmanaged Unions

An example of a structure is OSVERSIONINFOEX structure that encapsulates operating system version information together. For those who are somewhat familiar with DirectX, they may find that DirectX API relies heavily on structures.

As you know, because there is no compatibility between .NET and unmanaged code, data must undergo some conversion routines for transmitting from the managed code to the unmanaged server and vice versa, and compound types are no exception.

In the next section, we will focus of the first kind, structures.

Marshaling Unmanaged Structures

How to Marshal a Structure

Unmanaged structures can be marshaled as managed structures or even classes. Choosing between a managed structure and a class is up to you, there are no rules to follow. However, when marshaling as managed classes, there are some limitations with the passing mechanism as we will see later in this chapter.

When marshaling structures in the managed environment, you must take into consideration that while you access a variable into your by its name, Windows accesses it via its address (i.e. position) inside the memory, it does not care about field name, but it cares about its location and size. Therefore, the memory layout and size of the type are very crucial.

You can marshal an unmanaged structure in few steps:

  1. Create the marshaling type either a managed structure or a class.
  2. Add the type fields (variables) only. Again, layout and size of the type are very crucial. Therefore, fields must be ordered as they are defined, so that the Windows can access them correctly.
  3. Decorate your type with StructLayoutAttribute attribute specifying the memory layout kind.

Handling Memory Layout Problem

When marshaling an unmanaged structure, you must take care of how that type is laid-out into memory.

Actually, application memory is divided into blocks (in a 4-bytes base,) and every block has its own address. When you declare a variable or a type in your program it is stored inside the memory and got its memory address. Consequently, all data members inside a structure have their own addresses that are relative to the address of the beginning of the structure.

Consider the following structures:

Listing 3.1 SMALL_RECT and COORD Unmanaged Signature
typedef struct SMALL_RECT {
  SHORT Left;
  SHORT Top;
  SHORT Right;
  SHORT Bottom;
};

typedef struct COORD {
  SHORT X;
  SHORT Y;
};

When we declare those structures in our code they are laid-out into memory and got addresses like that:

Figure 3.1 How Memory is Laid-Out

Figure 3.1 How Memory is Laid-Out

Thus, you should keep in mind that the size and location of each of type members is very crucial and you strictly should take care of how this type is laid-out into the memory.

For now, you do not have to think about the last illustration. We will cover memory management in details in chapter 6.

For handling the memory layout problem, you must apply the StructLayoutAttribute attribute to your marshaling type specifying the layout kind using the LayoutKind property.

This property can take one of three values:

  • LayoutKind.Auto (Default):
    Lets the CLR chooses how the type is laid-out into memory. Setting this value prevents interoperation with this type, that means that you will not be able to marshal the unmanaged structure with this type, and if you tried, an exception will be thrown.
  • LayoutKind.Sequential:
    Variables of the type are laid-out sequentially. When setting this value ensure that all variables are on the right order as they are defined in the unmanaged structure.
  • LayoutKind.Explicit:
    Lets you control precisely each variable’s location inside the type. When setting this value, you must apply the FieldOffsetAttribute attribute to every variable in your type specifying the relative position in bytes of the variable to the start of the type. Note that when setting this value, order of variables becomes unimportant.

For the sake of simplicity, you should lay-out all of your types sequentially. However, when working with unions, you are required to explicitly control every variable’s location. Unions are covered in the next section.

We have said that you should add only the type members into the marshaling type, however, this is not always true. In structures where there is a member that you can set to determine the structure size (like the OPENFILENAME structure,) you can add your own members to the end of the structure. However, you should set the size member to the size of the entire structure minus the new members that you have added. This technique is discussed in details in chapter 6.

Try It Out!

The following example demonstrates how to marshal the famous structures SMALL_RECT and COORD. Both used earlier with the ScrollConsoleScreenBuffer() function in the last chapter. You can check code listing 3.1 earlier in this chapter for the definition of the structures.

Next is the managed signature for both the structures. Note that you can marshal them as managed classes too.

Listing 3.2 SMALL_RECT and COORD Managed Signature
// Laying-out the structure sequentially
[StructLayout(LayoutKind.Sequential)]
//public class SMALL_RECT
public struct SMALL_RECT
{
    // Because we are laying the structure sequentially,
    // we preserve field order as they are defined.

    public UInt16 Left;
    public UInt16 Top;
    public UInt16 Right;
    public UInt16 Bottom;
}

// The same as SMALL_RECT applies to COORD
[StructLayout(LayoutKind.Sequential)]
//public struct COORD
public struct COORD
{
    public UInt16 X;
    public UInt16 Y;
}

Marshaling Unions

A Short Speech About Unions

A union is a memory location that is shared by two or more different types of variables. A union provides a way for interpreting the same bit pattern in two or more different ways (or forms.)

In fact, unions share structures lots of characteristics, like the way they defined and marshaled. It might be helpful to know that, like structures, unions can be defined inside a structure or even as a single entity. In addition, unions can define compound types inside, like structures too.

To understand unions, we will take a simple example. Consider the following union:

Listing 3.3 SOME_CHARACTER Unmanaged Signature
typedef union SOME_CHARACTER {
  int i;
  char c;
};

This was a simple union defines a character. It declared two members, i and c, it defined them in the same memory location. Thus, it provides two ways for accessing the character, by its code (int) and by its value (char). For this to work it allocates enough memory storage for holding the largest member of the union and that member is called container. Other members will overlap with the container. In our case, the container is i because it is 4 bytes (on Win32, 16 on Win16), while c is only 1 byte. Figure 3.2 shows how the memory is allocated for the union.

Figure 3.2 SOME_CHARACTER Union

Figure 3.2 SOME_CHARACTER Union

Because the two members are sharing the same memory location, when you change one member the other is changed too. Consider the following C example:

Listing 3.4 Unions Example 1
int main()
{
	union CHARACTER ch;

	ch.i = 65;			// 65 for A
	printf("c = %c", ch.c);	// prints 'A'
	printf("\n");

	ch.c += 32;			// 97 for a
	printf("i = %d", ch.i);	// prints '97'
	printf("\n");

	return 0;
}

When you change any of the members of the union, other members change too because they are all share the same memory address.

Now consider the same example but with values that won’t fit into the char member:

Listing 3.5 Unions Example 2
int main()
{
	union CHARACTER ch;

	ch.i = 330;
	printf("c = %c", ch.c);	// prints 'J'
	printf("\n");			// Ops!

	ch.c += 32;
	printf("i = %d", ch.i);	// prints '362'
	printf("\n");

	return 0;
}

What happened? Because char is 1 bye wide, it interprets only the first 8 bits of the union that are equal to 32.

The same rule applies if you add another member to the union. See the following example. Notice that order of member declarations doesn’t matter.

Listing 3.6 Unions Example 3
int main()
{
	union {
		int i;
		char c;
		short n;
	} ch;

	ch.i = 2774186;

	printf("i = %d", ch.i);
	printf("\n");
	printf("c = %i", (unsigned char)ch.c);
	printf("\n");
	printf("n = %d", ch.n);
	printf("\n");

	return 0;
}

Now, member i, the container, interprets the 32 bits. Member c, interprets the first 8 bits (notice that we converted it to unsigned char to not to show the negative value.) Member n, interprets the first high word (16 bits.)

You might ask: Why I need unions at all? I could easily use the cast operator to convert between data types!

The answer is very easy. Unions come very efficient when casting between types require much overhead. Consider the following example: You are about to write an integer to a file. Unfortunately, there are no functions in the C standard library that allow you to write an int to a file, and using fwrite() function requires excessive overhead. The perfect solution is to define a union that contains an integer and a character array to allow it to be interpreted as an integer and as a character array when you need to pass it to fwrite() for example. See the following code snippet:

Listing 3.7 Unions Example 4
typedef union myval{
	int i;
	char str[4];
};

In addition, unions offer you more performance than casts. Moreover, your code will be more readable and efficient when you use unions.

More on how unions are laid-out into memory in chapter 6.

How to Marshal a Union

You can marshal a union the same way as you marshal structures, except that because of the way that unions laid-out into memory, you will need to explicitly set variable positions inside the type.

Follow these steps to marshal a union:

  1. Create your marshaling type, no matter whether your marshaling type is a managed structure or class. Again, classes require special handling when passed as function arguments. Passing mechanism is covered soon.
  2. Decorate the type with the StructLayoutAttribute attribute specifying LayoutKind.Explicit for the explicit layout kind.
  3. Add the type fields. Do not add fields other than those defined in the unmanaged signature. Because we are controlling the type layout explicitly, order of fields is not important.
  4. Decorate every field with the FieldOffsetAttribute attribute specifying the absolute position in bytes of the member from the start of the type.

The following example demonstrates how to marshal our SOME_CHARACTER union.

Listing 3.8 SOME_CHARACTER Managed Signature

// Unions require explicit memory layout
[StructLayout(LayoutKind.Explicit)]
//public class SOME_CHARACTER
public struct SOME_CHARACTER
{
    // Both members located on the same
    // position in the beginning of the union

    // This is the continer it is 4 bytes
    [FieldOffset(0)]
    [MarshalAs(UnmanagedType.U4)]
    public int i;
    // This is only 1 byte. Therefore, it is contained
    [FieldOffset(0)]
    public char c;
}

public static void Main()
{
    SOME_CHARACTER character = new SOME_CHARACTER();

    // The code for letter 'A'
    character.i = 65;
    // Should prints 'A'
    Console.WriteLine("c = {0}", character.c);

    character.c = 'B';
    // Should prints 66
    Console.WriteLine("i = {0}", character.i);
}

From the last code, we learn that…

  • Unions are marshaled like structures, they can be marshaled as either managed structures or classes.
  • Setting StructLayoutAttribute.LayoutKind to LayoutKind.Explicit allows us to exactly control the memory location of our members.
  • We use the FieldOffsetAttribute to specify the starting location in bytes of the field into the type in memory.
  • To create the union between the fields, we set both the fields to the same memory location.
  • In the example, member i occupies byte 0 through byte 4, and member c occupies byte 0 through byte 1.
  • If we do not need the benefits of unions, we can omit member c because it is contained inside the range of member i. However, we cannot omit member c because it is the container.
  • When we change either one of the union variables, the other variable changes too because they share the same memory address.

Unions with Arrays

Another example of a union is as following:

Listing 3.9 UNION_WITH_ARRAY Unmanaged Signature
typedef union UNION_WITH_ARRAY
{
    INT number;
    CHAR charArray[128];
};

This union must be marshaled in a special way because managed code does not permit value types and reference types to overlap.

As a refresher, a value-type is the type stored in the memory stack; it inherits from System.ValueType. All primitive data types, structures, and enumerations are considered value-types. On the other hand, reference-types are those types stored in the memory heap; they inherit from System.Object. Most types in .NET are reference-types (except System.ValueType and its descendents of course.)

That is, all value-types inherit -directly or indirectly- from System.ValueType.

As a result, we cannot union both members of our example, because whether marshaling the second variable charArray as an array, a System.String, or as a System.Text.StringBuilder, it is still a reference-type. Therefore, we have to leave the benefits of unions and marshal only a single member. For our example, we will create two marshaling types for our union, one with the first member marshaled, and the other with the other member.

As we know, the layout and size of the type inside the memory is the most crucial. Therefore, we must preserve the layout and size of our union. This union has a 128 bytes array as a container and only one member contained, and this member is only 2-bytes. Therefore, we have two choices, to marshal the union with the container member, or to marshal it with the contained member but to extend it enough to be as large as the container. In this example, we will take the two approaches.

Try It Out!

The following are two code segments. The first demonstrates how to marshal only the second member which is the container, while the second demonstrates how to marshal the first member.

Listing 3.10 UNION_WITH_ARRAY Union Managed Signature
// Setting StructLayoutAttribute.CharSet
// ensures the correct encoding for all
// string members of the union in our example
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
//public struct UNION_WITH_ARRAY_1
public struct UNION_WITH_ARRAY_1
{
    // As we know, character arrays can be marshaled
    // as either an array or as a string

    // Setting MarshalAsAttribute is required
    // for the array and the string

    //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
    //public char[] charArray;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string charArray;
}

// StructLayoutAttribute.Size determines
// the size -in bytes- of the type.
// If the size specified is larger than
// members’ size, the last member will be extended
// Because this is only a single
// member, we laid it out sequentially.
[StructLayout(LayoutKind.Sequential, Size = 128)]
//public class UNION_WITH_ARRAY_2
public struct UNION_WITH_ARRAY_2
{
    [MarshalAs(UnmanagedType.I2)]
    public short number;
}

For more information about marshaling arrays, refer to the next chapter.

Value-Types and Reference-Types

In the realm of .NET, types are broken into two categories:

  • Value-Types:
    These types are stored in the memory stack. They are destroyed when their scope ends, therefore, they are short-lived. Types of this category are all types inherit from System.ValueType (like all primitive data types, structures, and enumerations.)
  • Reference-Types:
    These types are stored in the memory heap. They are controlled by the Garbage Collector (GC,) therefore, they may retain in memory for a long while. Reference-types are all types -directly or indirectly- inherit from System.Object (except System.ValueType and descendants of course.) All .NET classes fall in this category.

Stack and heap! Confused? Check chapter 6 for more details.

Talking about value-types and reference-types leads us to talk about the passing mechanism. And that is what the next section is devoted for.

Passing Mechanism

In the last chapter, we have talked about the passing mechanism with simple types and how it affects the call. Actually, all we have learnt is applied to the compound types too.

As a refresher, when a type passed by value, a copy of type passed to the function, not the value itself. Therefore, any changes to the type inside the function do not affect the original copy. On the other hand, passing a type by reference passes a pointer to the value to the function. In other words, the value itself is passed. Therefore, any changes to the type inside the function are seen by the caller.

Functions require the type passed to be passed either by value or by reference. Plus, they require the argument to be passed by reference only if the argument will be changed inside.

Moreover, an argument passed by reference can be passed either as Input/Output (In/Out) or Output (Out). In/Out arguments used by the function for receiving the input from the caller and posting the changes back to him. Therefore, In/Out arguments must be initialized before handing them to the function. On the other hand, output (Out) arguments are only used for returning output to the caller. Therefore, they do not require pre-initialization because the function will initialize them.

All of the information learnt from the last chapter is applied to this chapter too.

Compound types also can be passed by value or by reference. When passing by value, no changes need to be applied. On the other hand passing a type by reference requires some changes to the PInvoke method and the call itself.

If you are marshaling as a structure, you may add the ref modifier to the parameter. However, classes are -by default- reference-types. Thus, they are normally passed by reference and they cannot be passed by value. Therefore, they do not need the ref modifier.

On the other hand, if you are passing the type as output (Out,) you will need to add the out modifier whether it is a structure or a class.

As you know, you can decorate In/Out arguments with both InAttribute and OutAttribute attributes. For Out arguments, specify OutAttribute attribute only.

Notice that there is a big difference between managed and unmanaged classes. Unmanaged classes are -by default- value-types. Manager classes are reference-types.

The following example demonstrates the PInvoke method for the function GetVersionEx(). This function requires a single In/Out argument. That argument is of the type OSVERSIONINFO.

The function uses OSVERSIONINFO’s dwOSVersionInfoSize field as input from the caller for determining the type size, and it uses the remaining arguments as output for sending the version information back. Therefore, the function requires the argument to be passed by reference as In/Out.

Next is the definition of the function along with the structure:

Listing 3.11 GetVersionEx() Unmanaged Signature
BOOL GetVersionEx(
  OSVERSIONINFO lpVersionInfo
);

typedef struct OSVERSIONINFO{
  DWORD dwOSVersionInfoSize;
  DWORD dwMajorVersion;
  DWORD dwMinorVersion;
  DWORD dwBuildNumber;
  DWORD dwPlatformId;
  TCHAR szCSDVersion[128];
};

In addition, this is the managed version with the text code:

Listing 3.12 Retrieving System Version Information Sample
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetVersionEx
    ([param: In, Out]
    // If a class remove the "ref" keyword
    ref OSVERSIONINFO lpVersionInfo);

[StructLayout(LayoutKind.Sequential)]
//public class OSVERSIONINFO
public struct OSVERSIONINFO
{
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwOSVersionInfoSize;
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwMajorVersion;
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwMinorVersion;
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwBuildNumber;
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwPlatformId;

    // Can be marshaled as an array too
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string szCSDVersion;
}

static void Main()
{
    OSVERSIONINFO info = new OSVERSIONINFO();
    info.dwOSVersionInfoSize = (uint)Marshal.SizeOf(info);

    //GetVersionEx(info);
    GetVersionEx(ref info);

    Console.WriteLine("System Version: {0}.{1}",
        info.dwMajorVersion, info.dwMinorVersion);
}

More about the passing mechanism in chapter 6.

Compound Types and Character Encoding

As you know, the size and layout of the marshaling type is the most important. If the compound type contains a textual data, sure special handling should be taken to ensure correct marshaling of the data.

You already know that the character encoding can be either ANSI or Unicode.

When a string is ANSI-encoded, every character reserves only a single byte of application memory. On the other hand, every character in a Unicode-encoded string reserves two bytes of the memory. Therefore, a string like “C-Sharp” with 7 characters reserves 7 bytes if ANSI-encoded and 14 bytes if Unicode-encoded.

You can determine the character encoding of the compound type by specifying the CharSet property of the StructLayoutAttribute attribute. This property can take one of several values:

  • CharSet.Auto (CLR Default):
    Strings encoding varies based on operating system; it is Unicode-encoded on Windows NT and ANSI-encoded on other versions of Windows.
  • CharSet.Ansi (C# Default):
    Strings are always 8-bit ANSI-encoded.
  • CharSet.Unicode:
    Strings are always 16-bit Unicode-encoded.
  • CharSet.None:
    Obsolete. Has the same behavior as CharSet.Ansi.

Take into consideration that if you have not set the CharSet property, CLR automatically sets it to CharSet.Auto. However, some languages override the default behavior. For example, C# defaults to CharSet.Ansi.

In addition, you can determine the character encoding at a granular level by specifying the CharSet property of the MarshalAsAttribute attribute applied to the member.

Real-World Examples

The DEVMODE Structure

Now, we are going to dig into real-world examples. In the first example, we are going to marshal one of the most complex compound structures in the Windows API, it is the DEVMODE structure.

If you have worked with GDI, you will be somewhat familiar with this structure. It encapsulates information about initialization and environment of a printer or a display device. It is required by many functions like EnumDisplaySettings(), ChangeDisplaySettings() and OpenPrinter().

The complexity of this structure comes because of few factors. Firstly, there are unions defined inside the structure. In addition, the definition of this structure defers from a platform to another. As we will see, the structure defines some members based on the operating system.

Here is the definition of DEVMODE structure along with the POINTL structure that is referenced by DEVMODE.

Listing 3.13 DEVMODE and POINTL Unmanaged Signature
typedef struct DEVMODE {
  BCHAR  dmDeviceName[CCHDEVICENAME];
  WORD   dmSpecVersion;
  WORD   dmDriverVersion;
  WORD   dmSize;
  WORD   dmDriverExtra;
  DWORD  dmFields;
  union {
    struct {
      short dmOrientation;
      short dmPaperSize;
      short dmPaperLength;
      short dmPaperWidth;
      short dmScale;
      short dmCopies;
      short dmDefaultSource;
      short dmPrintQuality;
    };
    POINTL dmPosition;
    DWORD  dmDisplayOrientation;
    DWORD  dmDisplayFixedOutput;
  };
  short  dmColor;
  short  dmDuplex;
  short  dmYResolution;
  short  dmTTOption;
  short  dmCollate;
  BYTE  dmFormName[CCHFORMNAME];
  WORD  dmLogPixels;
  DWORD  dmBitsPerPel;
  DWORD  dmPelsWidth;
  DWORD  dmPelsHeight;
  union {
    DWORD  dmDisplayFlags;
    DWORD  dmNup;
  }
  DWORD  dmDisplayFrequency;
#if(WINVER >;= 0x0400)
  DWORD  dmICMMethod;
  DWORD  dmICMIntent;
  DWORD  dmMediaType;
  DWORD  dmDitherType;
  DWORD  dmReserved1;
  DWORD  dmReserved2;
#if (WINVER >;= 0x0500) || (_WIN32_WINNT >;= 0x0400)
  DWORD  dmPanningWidth;
  DWORD  dmPanningHeight;
#endif
#endif /* WINVER >;= 0x0400 */
};
typedef struct POINTL {
  LONG x;
  LONG y;
};

You might have noticed that two unions are defined inside the structure. In addition, a structure is defined inside the first union! Moreover, the last 8 members are not supported in Windows NT. Plus, the very last two members, dmPanningWidth and dmPanningHeight, are not supported in Windows 9x (95/98/ME.)

When working with Windows API, you should take care of operating system compatibility. Some functions, for instance, are not supported on certain operating systems (e.g. most Unicode versions are not supported on Win9x.) Other functions take arguments that vary based on the OS (i.e. EnumPrinters() function.) If your application tried to call a function, for instance, that is not supported by the current operating system, the call would fail.

If you need your application to be portable to every platform, you will need to create three versions of the structure, one for Windows ME and its ascendants, one for Windows NT, and the last for Windows 2000 and higher versions. In addition, you will need to create three overloads of every function require DEVMODE structure; three overloads for the three structures. For the sake of simplicity, we will assume that you are working with Windows 2000 or a higher version. Thus, we will marshal all members of the structure.

The following is the managed version of both DEVMODE and POINTL structures:

Listing 3.14 DEVMODE and POINTL Managed Signature
// Setting StructLayout.LayoutKind to LeyoutKind.Explicit to allow
// precisely choosing of member position. It is required for unions
// This structure is 156-bytes
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
//public class DEVMODE
public struct DEVMODE
{
    // You can define the following constant
    // BUT OUTSIDE THE STRUCTURE
    // because you know that size and layout of the structure
    // is very important
    // CCHDEVICENAME = 32 = 0x50
    [FieldOffset(0)]
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public Char[] dmDeviceName;
    // In addition you can define the last character array
    // as following:
    //MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    //public string dmDeviceName;

    // After the 32-bytes array
    [FieldOffset(32)]
    [MarshalAs(UnmanagedType.U2)]
    public UInt16 dmSpecVersion;

    [FieldOffset(34)]
    [MarshalAs(UnmanagedType.U2)]
    public UInt16 dmDriverVersion;

    [FieldOffset(36)]
    [MarshalAs(UnmanagedType.U2)]
    public UInt16 dmSize;

    [FieldOffset(38)]
    [MarshalAs(UnmanagedType.U2)]
    public UInt16 dmDriverExtra;

    [FieldOffset(40)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmFields;

    // ************ Union Start ************
    // Because DEVMODE_PRINT_SETTINGS is the hugest member and it is
    // 16-bytes, it is the container for other members
    // Remeber, you cannot emit the container
    [FieldOffset(44)]
    public DEVMODE_PRINT_SETTINGS dmSettings;

    // Positioned within DEVMODE_PRINT_SETTINGS
    // It is 8-bytes only
    [FieldOffset(44)]
    public POINTL dmPosition;

    // Positioned within DEVMODE_PRINT_SETTINGS
    [FieldOffset(44)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmDisplayOrientation;

    // Positioned within DEVMODE_PRINT_SETTINGS
    [FieldOffset(44)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmDisplayFixedOutput;
    // ************* Union End *************

    // Because DEVMODE_PRINT_SETTINGS structure
    // is 16-bytes, dmColor is positioned on byte 60
    [FieldOffset(60)]
    [MarshalAs(UnmanagedType.I2)]
    public Int16 dmColor;

    [FieldOffset(62)]
    [MarshalAs(UnmanagedType.I2)]
    public Int16 dmDuplex;

    [FieldOffset(64)]
    [MarshalAs(UnmanagedType.I2)]
    public Int16 dmYResolution;

    [FieldOffset(66)]
    [MarshalAs(UnmanagedType.I2)]
    public Int16 dmTTOption;

    [FieldOffset(70)]
    [MarshalAs(UnmanagedType.I2)]
    public Int16 dmCollate;

    // CCHDEVICENAME = 32 = 0x50
    [FieldOffset(72)]
    [MarshalAs(UnmanagedType.ByValArray,
        SizeConst = 32,
        ArraySubType = UnmanagedType.U1)]
    public Byte[] dmFormName;

    // After the 32-bytes array
    [FieldOffset(102)]
    [MarshalAs(UnmanagedType.U2)]
    public UInt16 dmLogPixels;

    [FieldOffset(104)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmBitsPerPel;

    [FieldOffset(108)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmPelsWidth;

    [FieldOffset(112)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmPelsHeight;

    // ************ Union Start ************
    // Because both members are 4-bytes, the union is 4-bytes
    // and its members are overlapped
    // Again, you cannot emit the container
    // Except if both are equal, you can emit anyone of them
    [FieldOffset(116)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmDisplayFlags;

    [FieldOffset(116)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmNup;
    // ************* Union End *************

    [FieldOffset(120)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmDisplayFrequency;

    [FieldOffset(124)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmICMMethod;

    [FieldOffset(128)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmICMIntent;

    [FieldOffset(132)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmMediaType;

    [FieldOffset(136)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmDitherType;

    [FieldOffset(140)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmReserved1;

    [FieldOffset(144)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmReserved2;

    [FieldOffset(148)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmPanningWidth;

    [FieldOffset(152)]
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dmPanningHeight;
}

// 16-bytes structure
[StructLayout(LayoutKind.Sequential)]
//public class DEVMODE_PRINT_SETTINGS
public struct DEVMODE_PRINT_SETTINGS
{
    public short dmOrientation;
    public short dmPaperSize;
    public short dmPaperLength;
    public short dmPaperWidth;
    public short dmScale;
    public short dmCopies;
    public short dmDefaultSource;
    public short dmPrintQuality;

}

// 8-bytes structure
[StructLayout(LayoutKind.Sequential)]
//public class POINTL
public struct POINTL
{
    public Int32 x;
    public Int32 y;
}

As we have said earlier in the previous chapter, this writing assumes 32-bit versions of Windows. For instance, in the DEVMODE example, we have assumed that DWORDs are 4 bytes. If you want to port your application to a 64-bit machine, DWORDs should be considered as 8 bytes.

Lengthy, isn’t it? DEVMODE is one of the lengthy and compound GDI structures. If you want to learn more about laying out structure into memory, refer to chapter 6 “Memory Management.”

From the last code we learn that…

  • Whether the union defined as a single entity or inside a structure, you will need to lay-out the type explicitly into memory to allow defining two or more variables at the same memory location.
  • When setting the memory layout explicitly, we apply the FieldOffsetAttribute attribute to the variable specifying the location -in bytes- of the variable from the start of the type.
  • In the union that defines a structure inside, we marshaled the structure outside the union and referred it to be the container of other members. Chapter 6 demonstrates other techniques for laying-out structures into memory.

Working with Display Settings

The follows example shows how you can access and modify display settings programmatically using C# and Windows API. In this example we will create four functions, one retrieves current display settings, another enumerates available display modes, the third changes current display settings, and the last changes screen orientation (i.e. rotates the screen.)

For our example, we will use the DEVMODE and POINTL structures that we have marshaled previously. In addition, we will make use of two new Windows API functions, EnumDisplaySettings and ChangeDisplaySettings. The following is the unmanaged signature of both functions:

Listing 3.15 EnumDisplaySettings() and ChangeDisplaySettings() Unmanaged Signature
BOOL EnumDisplaySettings(
  LPCTSTR lpszDeviceName,            // display device
  DWORD iModeNum,                    // graphics mode
  [In, Out] LPDEVMODE lpDevMode      // graphics mode settings
);

LONG ChangeDisplaySettings(
  LPDEVMODE lpDevMode,               // graphics mode
  DWORD dwflags                      // graphics mode options
);

For more information about these functions, refer to the MSDN documentation.

The next is the managed version of the functions:

Listing 3.16 EnumDisplaySettings() and ChangeDisplaySettings() Managed Signature
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean EnumDisplaySettings(
    [param: MarshalAs(UnmanagedType.LPTStr)]
    string lpszDeviceName,
    [param: MarshalAs(UnmanagedType.U4)]
    int iModeNum,
    [In, Out]
    ref DEVMODE lpDevMode);

[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.I4)]
public static extern int ChangeDisplaySettings(
    [In, Out]
    ref DEVMODE lpDevMode,
    [param: MarshalAs(UnmanagedType.U4)]
    uint dwflags);

Finally, those are our four functions that utilize the native functions:

Listing 3.17 Accessing/Modifying Display Settings Sample
public static void GetCurrentSettings()
{
    DEVMODE mode = new DEVMODE();
    mode.dmSize = (ushort)Marshal.SizeOf(mode);

    if (EnumDisplaySettings(null,
        ENUM_CURRENT_SETTINGS, ref mode) == true) // Succeeded
    {
        Console.WriteLine("Current Mode:\n\t" +
            "{0} by {1}, {2} bit, {3} degrees, {4} hertz",
            mode.dmPelsWidth, mode.dmPelsHeight,
            mode.dmBitsPerPel, mode.dmDisplayOrientation * 90,
            mode.dmDisplayFrequency);
    }
}

public static void EnumerateSupportedModes()
{
    DEVMODE mode = new DEVMODE();
    mode.dmSize = (ushort)Marshal.SizeOf(mode);

    int modeIndex = 0; // 0 = The first mode

    Console.WriteLine("Supported Modes:");

    while (EnumDisplaySettings(null,
        modeIndex, ref mode) == true) // Mode found
    {
        Console.WriteLine("\t{0} by {1}, {2} bit, " +
            "{3} degrees, " +
            "{4} hertz",
            mode.dmPelsWidth, mode.dmPelsHeight,
            mode.dmBitsPerPel, mode.dmDisplayOrientation * 90,
            mode.dmDisplayFrequency);

        modeIndex++; // The next mode
    }
}

public static void ChangeDisplaySettings
    (int width, int height, int bitCount)
{
    DEVMODE originalMode = new DEVMODE();
    originalMode.dmSize = (ushort)Marshal.SizeOf(originalMode);

    // Retrieving current settings to edit them
    EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref originalMode);

    // Making a copy of the current settings
    // to allow reseting to the original mode
    DEVMODE newMode = originalMode;

    // Changing the settings
    newMode.dmPelsWidth = (uint)width;
    newMode.dmPelsHeight = (uint)height;
    newMode.dmBitsPerPel = (uint)bitCount;

    // Capturing the operation result
    int result = ChangeDisplaySettings(ref newMode, 0);

    if (result == DISP_CHANGE_SUCCESSFUL)
    {
        Console.WriteLine("Succeeded.\n");

        // Inspecting the new mode
        GetCurrentSettings();

        Console.WriteLine();

        // Waiting for seeing the results
        Console.ReadKey(true);

        ChangeDisplaySettings(ref originalMode, 0);
    }
    else if (result == DISP_CHANGE_BADMODE)
        Console.WriteLine("Mode not supported.");
    else if (result == DISP_CHANGE_RESTART)
        Console.WriteLine("Restart required.");
    else
        Console.WriteLine("Failed. Error code = {0}", result);
}

public static void RotateScreen(bool clockwise)
{
    // Retrieving current settings
    // ...

    // Rotating the screen
    if (clockwise)
        if (newMode.dmDisplayOrientation <; DMDO_270)
            newMode.dmDisplayOrientation++;
        else
            newMode.dmDisplayOrientation = DMDO_DEFAULT;
     else
        if (newMode.dmDisplayOrientation >; DMDO_DEFAULT)
            newMode.dmDisplayOrientation--;
        else
            newMode.dmDisplayOrientation = DMDO_270;

    // Swapping width and height;
    uint temp = newMode.dmPelsWidth;
    newMode.dmPelsWidth = newMode.dmPelsHeight;
    newMode.dmPelsHeight = temp;

    // Capturing the operation result
    // ...
}

The Console Library

There are functionalities of console applications that are not accessible from the .NET Framework like clearing the console screen and moving a text around.

The following sample shows a tiny library for console applications. It contains some of the common functionalities of the console (like writing and reading data) along with new functionalities added.

Listing 3.18 The Console Library Sample
SafeNativeMethods.cs

using System;
using System.Runtime.InteropServices;
using System.Text;

/// <summary>
/// Safe native functions
/// </summary>
internal static class SafeNativeMethods
{
    /// <summary>
    /// Standard input device.
    /// </summary>
    public const int STD_INPUT_HANDLE = -10;
    /// <summary>
    /// Standard output device.
    /// </summary>
    public const int STD_OUTPUT_HANDLE = -11;
    /// <summary>
    /// Standard error device (usually the output device.)
    /// </summary>
    public const int STD_ERROR_HANDLE = -12;

    /// <summary>
    /// White space character for clearing the screen.
    /// </summary>
    public const char WHITE_SPACE = ' ';

    /// <summary>
    /// Retrieves a handle for the console standard input, output, or error device.
    /// </summary>
    /// <param name="nStdHandle">The standard device of which to retrieve handle for.</param>
    /// <returns>The handle for the standard device selected.
    /// Or an invalid handle if the function failed.</returns>
    [DllImport("Kernel32.dll")]
    public static extern IntPtr GetStdHandle([param: MarshalAs(UnmanagedType.I4)] int nStdHandle);

    /// <summary>
    /// Writes a character string to the console buffer starting from the current cursor position.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="lpBuffer">The string of which to write.</param>
    /// <param name="nNumberOfCharsToWrite">Number of characters to write.</param>
    /// <param name="lpNumberOfCharsWritten">Outputs the number of characters written.</param>
    /// <param name="lpReserved">Reserved.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool WriteConsole
        (IntPtr hConsoleOutput,
        string lpBuffer,
        [param: MarshalAs(UnmanagedType.U4)] uint nNumberOfCharsToWrite,
        [param: MarshalAs(UnmanagedType.U4)] [Out] out uint lpNumberOfCharsWritten,
        [param: MarshalAs(UnmanagedType.U4)]
        uint lpReserved);

    /// <summary>
    /// Read a character string from the console buffer starting from the current cursor position.
    /// </summary>
    /// <param name="hConsoleInput">A handle for the opened input device.</param>
    /// <param name="lpBuffer">The string read from the buffer.</param>
    /// <param name="nNumberOfCharsToRead">The number of characters to read.</param>
    /// <param name="lpNumberOfCharsRead">Outputs the number of characters read.</param>
    /// <param name="lpReserved">Reserved.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool ReadConsole(
        IntPtr hConsoleInput,
        StringBuilder lpBuffer,
        [param: MarshalAs(UnmanagedType.U4)] uint nNumberOfCharsToRead,
        [param: MarshalAs(UnmanagedType.U4)] [Out] out uint lpNumberOfCharsRead,
        [param: MarshalAs(UnmanagedType.U4)] uint lpReserved);

    /// <summary>
    /// Retrieves information about the console cursor such as the size and visibility.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="lpConsoleCursorInfo">The cursor info.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetConsoleCursorInfo(
        IntPtr hConsoleOutput,
        [Out] out CONSOLE_CURSOR_INFO lpConsoleCursorInfo);

    /// <summary>
    /// Sets the console cursor properties as the size and visibility.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="lpConsoleCursorInfo">The cursor info.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("kernel32.dll")]

    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetConsoleCursorInfo(
        IntPtr hConsoleOutput,
        ref CONSOLE_CURSOR_INFO lpConsoleCursorInfo);

    /// <summary>
    /// Moves a block of data in a screen buffer.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="lpScrollRectangle">The coordinates of the block to move.</param>
    /// <param name="lpClipRectangle">The coordinates affected by the scrolling.</param>
    /// <param name="dwDestinationOrigin">The coordinates represents
    /// the new location of the block.</param>
    /// <param name="lpFill">Specifies the character and color info for the cells
    /// left empty after the move.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    /// <remarks>
    /// Because we are going to set the <paramref name="lpClipRectangle"/> to NULL,
    /// we marshaled it as IntPtr so we can set it to null using IntPtr.Zero.
    /// If you do need to set its value, you can marshal it as SMALL_RECT.
    /// </remarks>
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool ScrollConsoleScreenBuffer(
        IntPtr hConsoleOutput,
        ref SMALL_RECT lpScrollRectangle,
        IntPtr lpClipRectangle,
        COORD dwDestinationOrigin,
        ref CHAR_INFO lpFill);

    /// <summary>
    /// Retrieves information about the specified console screen buffer.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the device of which to get its
    /// information.</param>
    /// <param name="lpConsoleScreenBufferInfo">Outputs the information of the
    /// specified screen buffer.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("Kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetConsoleScreenBufferInfo
        (IntPtr hConsoleOutput,
        [Out] out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

    /// <summary>
    /// Fills the console buffer with a specific character.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="cCharacter">The character of which to fill the buffer width.
    /// Setting this character to a white space means clearing the cells.</param>
    /// <param name="nLength">The number of cells to fill.</param>
    /// <param name="dwWriteCoord">The location of which to start filling.</param>
    /// <param name="lpNumberOfCharsWritten">Outputs the number of characters written.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("Kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool FillConsoleOutputCharacter
        (IntPtr hConsoleOutput,
        char cCharacter,
        [param: MarshalAs(UnmanagedType.U4)] uint nLength,
        COORD dwWriteCoord,
        [param: MarshalAs(UnmanagedType.U4)][Out] out uint lpNumberOfCharsWritten);

    /// <summary>
    /// Sets the console cursor to a specific position.
    /// </summary>
    /// <param name="hConsoleOutput">A handle for the opened output device.</param>
    /// <param name="dwCursorPosition">The new cursor position inside the console buffer.</param>
    /// <returns>True if succeeded, otherwise False.</returns>
    [DllImport("Kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetConsoleCursorPosition
        (IntPtr hConsoleOutput, COORD dwCursorPosition);
}

/// <summary>
/// Information about the screen buffer.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CONSOLE_SCREEN_BUFFER_INFO
{
    /// <summary>
    /// The size of the buffer.
    /// </summary>
    public COORD dwSize;
    /// <summary>
    /// The location of the cursor inside the buffer.
    /// </summary>
    public COORD dwCursorPosition;
    /// <summary>
    /// Additional attributes about the buffer write the fore color and back color.
    /// </summary>
    [MarshalAs(UnmanagedType.U2)]
    public ushort wAttributes;
    /// <summary>
    /// The location and bounds of the window.
    /// </summary>
    public SMALL_RECT srWindow;
    /// <summary>
    /// The maximum size of the window.
    /// </summary>
    public COORD dwMaximumWindowSize;
}

/// <summary>
/// Coordinates (X, Y).
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct COORD
{
    /// <summary>
    /// The location from the left (X).
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short X;
    /// <summary>
    /// The location from the top (Y).
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short Y;
}

/// <summary>
/// Defines the coordinates of the upper left and right bottom coordinates of a rectangle.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SMALL_RECT
{
    /// <summary>
    /// The X-coordinate of the upper left corner of the rectangle.
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short Left;
    /// <summary>
    /// The Y-coordinate of the upper left corner of the rectangle.
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short Top;
    /// <summary>
    /// The X-coordinate of the lower right corner of the rectangle.
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short Right;
    /// <summary>
    /// The Y-coordinate of the lower right corner of the rectangle.
    /// </summary>
    [MarshalAs(UnmanagedType.I2)]
    public short Bottom;
}

/// <summary>
/// Defines the console cursor info.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CONSOLE_CURSOR_INFO
{
    /// <summary>
    /// The size of the cursor. Usually 0.25 of the cell.
    /// </summary>
    [MarshalAs(UnmanagedType.U4)]
    public uint dwSize;
    /// <summary>
    /// If cursor is visible or not.
    /// </summary>
    [MarshalAs(UnmanagedType.Bool)]
    public bool bVisible;
}

/// <summary>
/// Defines a character information.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CHAR_INFO
{
    /// <summary>
    /// The character.
    /// </summary>
    public char Char;
    /// <summary>
    /// Additional attributes of the character like fore color and back color.
    /// </summary>
    [MarshalAs(UnmanagedType.U2)]
    public ushort Attributes;
}

ConsoleLib.cs

using System;
using System.Runtime.InteropServices;
using System.Text;

// Console horizontal text alignment.
public enum ConsoleTextAlignment
{
    /// <summary>
    /// Text is left aligned.
    /// </summary>
    Left,
    /// <summary>
    /// Text is right aligned.
    /// </summary>
    Right,
    /// <summary>
    /// Text is centered.
    /// </summary>
    Center
}

/// <summary>
/// Console standard devices.
/// </summary>
public enum ConsoleStandardDevice
{
    /// <summary>
    /// The input device.
    /// </summary>
    Input = SafeNativeMethods.STD_INPUT_HANDLE,
    /// <summary>
    /// The output device.
    /// </summary>
    Output = SafeNativeMethods.STD_OUTPUT_HANDLE,
    /// <summary>
    /// The error device (usually the output device.)
    /// </summary>
    Error = SafeNativeMethods.STD_ERROR_HANDLE
}

/// <summary>
/// Extension methods for the console.
/// </summary>
public static class ConsoleExtensions
{
    /// <summary>
    /// Clears the screen buffer.
    /// </summary>
    public static void ClearScreen()
    {
        // Clearing the screen starting from the first cell
        COORD location = new COORD();
        location.X = 0;
        location.Y = 0;

        ClearScreen(location);
    }
    /// <summary>
    /// Clears the screen buffer starting from a specific location.
    /// </summary>
    /// <param name="location">The location of which to start clearing
    /// the screen buffer.</param>
    public static void ClearScreen(COORD location)
    {
        // Clearing the screen starting from the specified location
        // Setting the character to a white space means clearing it
        // Setting the count to 0 means clearing to the end, not a specific length
        FillConsoleBuffer(location, 0, SafeNativeMethods.WHITE_SPACE);
    }

    /// <summary>
    /// Fills a specific cells with a specific character starting from a specific location.
    /// </summary>
    /// <param name="location">The location of which to start filling.</param>
    /// <param name="count">The number of cells starting
    /// from the location to fill.</param>
    /// <param name="character">The character to fill with.</param>
    public static void FillConsoleBuffer(COORD location, uint count, char character)
    {
        // Getting the console output device handle
        IntPtr handle = GetStandardDevice(ConsoleStandardDevice.Output);

        uint length;

        // If count equals 0 then user require clearing all the screen
        if (count == 0)
        {
            // Getting console screen buffer info
            CONSOLE_SCREEN_BUFFER_INFO info = GetBufferInfo(ConsoleStandardDevice.Output);
            // All the screen
            length = (uint)(info.dwSize.X * info.dwSize.Y);
        }
        else
            length = count;

        // The number of written characters
        uint numChars;

        // Calling the Win32 API function
        SafeNativeMethods.FillConsoleOutputCharacter(handle, character,
            length, location, out numChars);

        // Setting the console cursor position
        SetCursorPosition(location);
    }

    /// <summary>
    /// Rettrieves a handle for a specific device.
    /// </summary>
    /// <param name="device">The device of which to retrieve the handle for.</param>
    /// <returns>The handle for the specified device.</returns>
    public static IntPtr GetStandardDevice(ConsoleStandardDevice device)
    {
        // Calling the Win32 API function
        return SafeNativeMethods.GetStdHandle((int)device);
    }

    /// <summary>
    /// Writes an empty line to the console buffer on the current position of the cursor.
    /// </summary>
    public static void WriteLine()
    {
        WriteLine(string.Empty);
    }
    /// <summary>
    /// Writes specific text followed by a line terminator to the console buffer on
    /// the current position of the cursor.
    /// </summary>
    /// <param name="txt">The text to write.</param>
    public static void WriteLine(string txt)
    {
        WriteLine(txt, ConsoleTextAlignment.Left);
    }
    /// <summary>
    /// Writes specific text followed by a line terminator to the console buffer on the
    /// current position of the cursor with the specified line alignemnt.
    /// </summary>
    /// <param name="txt">The text to write.</param>
    /// <param name="alignment">The horizontal alignment of the text.</param>
    public static void WriteLine(string txt, ConsoleTextAlignment alignment)
    {
        Write(txt + Environment.NewLine, alignment);
    }
    /// <summary>
    /// Writes specific text to the console buffer on the current position of the cursor.
    /// </summary>
    /// <param name="txt">The text to write.</param>
    public static void Write(string txt)
    {
        Write(txt, ConsoleTextAlignment.Left);
    }
    /// <summary>
    /// Writes specific text to the console buffer on the current position of the cursor
    /// with the specified line alignment.
    /// </summary>
    /// <param name="txt">The text to write.</param>
    /// <param name="alignment">The horizontal alignment of the text.</param>
    public static void Write(string txt, ConsoleTextAlignment alignment)
    {
        if (alignment == ConsoleTextAlignment.Left)
            InternalWrite(txt);
        else
        {
            // Determining the location of which to begin writing
            CONSOLE_SCREEN_BUFFER_INFO info = GetBufferInfo(ConsoleStandardDevice.Output);

            COORD pos = new COORD();

            if (alignment == ConsoleTextAlignment.Right)
                pos.X = (short)(info.dwSize.X - txt.Length);
            else // Center
                pos.X = (short)((info.dwSize.X - txt.Length) / 2);

            pos.Y = info.dwCursorPosition.Y;

            // Changing the cursor position
            SetCursorPosition(pos);

            // Now writing on the current position
            InternalWrite(txt);
        }
    }
    /// <summary>
    /// Writing a specific text to the console output buffer starting from the
    /// current cursor position.
    /// </summary>
    /// <param name="txt">The text to write.</param>
    private static void InternalWrite(string txt)
    {
        // Required for the WriteConsole() function
        // It is the number of characters written
        uint count;
        // Getting the output handle
        IntPtr handle = GetStandardDevice(ConsoleStandardDevice.Output);
        // Calling the Win32 API function
        SafeNativeMethods.WriteConsole(handle, txt, (uint)txt.Length, out count, 0);
    }

    /// <summary>
    /// Shows or hides the cursor.
    /// </summary>
    /// <param name="show">Specifies whether to show the cursor or not.</param>
    public static void ShowCursor(bool show)
    {
        CONSOLE_CURSOR_INFO info;
        // Getting the output device
        IntPtr handle = GetStandardDevice(ConsoleStandardDevice.Output);

        // Getting the cursor info
        SafeNativeMethods.GetConsoleCursorInfo(handle, out info);

        // Determining the visibility of the cursor
        info.bVisible = show;

        // Setting the cursor info
        SafeNativeMethods.SetConsoleCursorInfo(handle, ref info);
    }

    /// <summary>
    /// Read the next line from the input device.
    /// </summary>
    /// <returns></returns>
    public static string ReadText()
    {
        // The buffer
        // Maximum number of characters is 256
        StringBuilder buffer = new StringBuilder(256);
        // Required for the function call
        uint count;
        // Getting the input device that's used for receiving user input
        SafeNativeMethods.ReadConsole(GetStandardDevice(ConsoleStandardDevice.Input), buffer,
            (uint)buffer.Capacity, out count, 0);
        // Returning the user input cutting up the line terminator
        return buffer.ToString().Substring(0, (int)(count - Environment.NewLine.Length));
    }

    /// <summary>
    /// Retrieves the buffer info of the specified device.
    /// </summary>
    /// <param name="device">The device of which to retrieve its information.</param>
    /// <returns>The buffer info of the specified device.</returns>
    public static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(ConsoleStandardDevice device)
    {
        // Returning the handle for the selected device
        IntPtr handle = GetStandardDevice(device);

        // Getting console screen buffer information
        CONSOLE_SCREEN_BUFFER_INFO info;
        SafeNativeMethods.GetConsoleScreenBufferInfo(handle, out info);

        return info;
    }

    /// <summary>
    /// Sets the cursor position in the buffer.
    /// </summary>
    /// <param name="pos">The coordinates of which to move the cursor to.</param>
    public static void SetCursorPosition(COORD pos)
    {
        // Getting the console output device handle
        IntPtr handle = SafeNativeMethods.GetStdHandle(SafeNativeMethods.STD_OUTPUT_HANDLE);

        // Moving the cursor to the new location
        SafeNativeMethods.SetConsoleCursorPosition(handle, pos);
    }

    /// <summary>
    /// Writes the buffer information to the screen.
    /// </summary>
    /// <param name="info">The information of which to write.</param>
    public static void WriteBufferInfo(CONSOLE_SCREEN_BUFFER_INFO info)
    {
        // Discovering console screen buffer information
        WriteLine("Console Buffer Info:");
        WriteLine("--------------------");

        WriteLine("Cursor Position:");
        WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "\t{0}, {1}",
            info.dwCursorPosition.X, info.dwCursorPosition.Y));

        // Is this information right?
        WriteLine("Maximum Window Size:");
        WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "\t{0}, {1}",
            info.dwMaximumWindowSize.X,
            info.dwMaximumWindowSize.Y));

        // Is this information right?
        WriteLine("Screen Buffer Size:");
        WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "\t{0}, {1}",
            info.dwSize.X, info.dwSize.Y));

        WriteLine("Screen Buffer Bounds:");
        WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture,
            "\t{0}, {1}, {2}, {3}",
            info.srWindow.Left, info.srWindow.Top,
            info.srWindow.Right, info.srWindow.Bottom));

        WriteLine("--------------------");
    }

    /// <summary>
    /// Writes the specific text followed by a line terminator to the left and moves
    /// it to the far right.
    /// </summary>
    /// <param name="txt">The text of which to write.</param>
    public static void MoveText(string txt)
    {
        // First, writing the text
        WriteLine(txt);

        // Getting the handle for the output device
        IntPtr handle = GetStandardDevice(ConsoleStandardDevice.Output);

        // Getting the screen buffer info for the output device
        CONSOLE_SCREEN_BUFFER_INFO screenInfo = GetBufferInfo(ConsoleStandardDevice.Output);

        // Selecting the text to be moved
        SMALL_RECT rect = new SMALL_RECT();
        rect.Left = 0; // The 1st cell
        rect.Top = (short)(screenInfo.dwCursorPosition.Y - 1); // The row of the text
        rect.Bottom = (short)(rect.Top); // Only a single line

        while (true)
        {
            // Moving to the right
            rect.Right = (short)(rect.Left + (txt.Length - 1));

            // Do not move it nore if we are in the far right of the buffer
            if (rect.Right == (screenInfo.dwSize.X - 1))
                break;

            // The character to fill the empty cells created after the move with
            CHAR_INFO charInfo = new CHAR_INFO();
            charInfo.Char = SafeNativeMethods.WHITE_SPACE; // For clearing the cells

            // Calling the API function
            SafeNativeMethods.ScrollConsoleScreenBuffer(handle, ref rect, IntPtr.Zero,
                new COORD() { X = (short)(rect.Left + 1), Y = rect.Top }, ref charInfo);

            // Blocking the thread for the user to see the effect
            System.Threading.Thread.Sleep(100);

            // Moving the rectangle
            rect.Left++;
        }
    }
}

Summary

After all, you learned that compound types are unmanaged structures and unions, and they called compound because they consisted of other types.

You learned that compound types can be marshaled as either a managed structure or a class. In addition, you learned how to lay-out the type into memory.

Again and again, the memory layout and size of the type is very crucial.

After that, you have worked with unions and learned that unions are simply a group of multiple variables share the same memory. In fact, it is the same memory location that is shared by one or more variables. Therefore, bits are represents in several ways.

Now it is the time for arrays. The next chapter discusses what arrays are and how to marshal them.

Download PDF and XPS versions of the book here.
Chapter 1: Introducing Marshaling
Chapter 2: Marshaling Simple Types
Chapter 3: Marshaling Compound Types

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)


Written By
Technical Lead
Egypt Egypt
Mohammad Elsheimy is a developer, trainer, and technical writer currently hired by one of the leading fintech companies in Middle East, as a technical lead.

Mohammad is a MCP, MCTS, MCPD, MCSA, MCSE, and MCT expertized in Microsoft technologies, data management, analytics, Azure and DevOps solutions. He is also a Project Management Professional (PMP) and a Quranic Readings college (Al-Azhar) graduate specialized in Quranic readings, Islamic legislation, and the Arabic language.

Mohammad was born in Egypt. He loves his machine and his code more than anything else!

Currently, Mohammad runs two blogs: "Just Like [a] Magic" (http://JustLikeAMagic.com) and "مع الدوت نت" (http://WithdDotNet.net), both dedicated for programming and Microsoft technologies.

You can reach Mohammad at elsheimy[at]live[dot]com

Comments and Discussions

 
QuestionGreat book! Pin
Member 824375326-Oct-13 6:35
Member 824375326-Oct-13 6:35 
QuestionArticle references to blog Pin
ledtech327-Nov-12 9:11
ledtech327-Nov-12 9:11 
QuestionNot able to downoad the complete PDF book from the blog Pin
Javed Akhtar Ansari12-Sep-12 0:29
Javed Akhtar Ansari12-Sep-12 0:29 
GeneralMy vote of 5 Pin
jsrjsr5-Jan-11 8:16
professionaljsrjsr5-Jan-11 8:16 
GeneralMy vote of 5 Pin
droka19844-Jan-11 20:14
droka19844-Jan-11 20:14 
GeneralMy vote of 5 Pin
ring_030-Dec-10 6:22
ring_030-Dec-10 6:22 
Great
Generalupdated Pin
Mohammad Elsheimy30-Mar-10 7:16
Mohammad Elsheimy30-Mar-10 7:16 
GeneralGood one, keep it up Pin
ss.teo23-Mar-10 16:44
ss.teo23-Mar-10 16:44 
GeneralRe: Good one, keep it up Pin
Mohammad Elsheimy24-Mar-10 3:48
Mohammad Elsheimy24-Mar-10 3:48 
GeneralMy vote of 5 Pin
Rozis23-Mar-10 13:57
Rozis23-Mar-10 13:57 
GeneralRe: My vote of 5 Pin
Mohammad Elsheimy24-Mar-10 10:15
Mohammad Elsheimy24-Mar-10 10:15 
GeneralRe: My vote of 5 Pin
Rozis25-Mar-10 12:21
Rozis25-Mar-10 12:21 
GeneralRe: My vote of 5 Pin
Mohammad Elsheimy26-Mar-10 3:24
Mohammad Elsheimy26-Mar-10 3:24 
GeneralRe: My vote of 5 Pin
ss.teo25-Mar-10 20:16
ss.teo25-Mar-10 20:16 
GeneralRe: My vote of 5 Pin
Mohammad Elsheimy26-Mar-10 3:25
Mohammad Elsheimy26-Mar-10 3:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.