Thursday, September 27, 2007

ListView header problem in C#

private void CreateMyListView()
{
// Create a new ListView control.
ListView listView1 = new ListView();
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200));

// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;

// Create three items and three sets of subitems for each item.
ListViewItem item1 = new ListViewItem("item1", 0);
// Place a check mark next to the item.
item1.Checked = true;
item1.SubItems.Add("1");
item1.SubItems.Add("2");
item1.SubItems.Add("3");
ListViewItem item2 = new ListViewItem("item2", 1);
item2.SubItems.Add("4");
item2.SubItems.Add("5");
item2.SubItems.Add("6");
ListViewItem item3 = new ListViewItem("item3", 0);
// Place a check mark next to the item.
item3.Checked = true;
item3.SubItems.Add("7");
item3.SubItems.Add("8");
item3.SubItems.Add("9");

// Create columns for the items and subitems.
listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);

//Add the items to the ListView.
listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 });
/*
// Create two ImageList objects.
ImageList imageListSmall = new ImageList();
ImageList imageListLarge = new ImageList();

// Initialize the ImageList objects with bitmaps.
imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage1.bmp"));
imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage2.bmp"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage1.bmp"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage2.bmp"));

//Assign the ImageList objects to the ListView.
listView1.LargeImageList = imageListLarge;
listView1.SmallImageList = imageListSmall;
*/
// Add the ListView to the control collection.
this.Controls.Add(listView1);
}

Labels:

Tuesday, September 11, 2007

MAPISendMail in C# application

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MAPIConsole
{
/*
[StructLayout(LayoutKind.Sequential)]
public struct MapiRecipDesc
{
public long Reserved;
public long RecipClass;
public string Name;
public string Address;
public long EIDSize;
public object EntryID;
}

[StructLayout(LayoutKind.Sequential)]
public struct MapiMessage
{
public long Reserved;
public string Subject;
public string NoteText;
public string MessageType;
public string DateReceived;
public string ConversationID;
public long Flags;
public object Originator;
public long RecipCount;
public MapiRecipDesc Recips;
public long FileCount;
public object Files;
}
*/


///
/// A MapiFileDesc structure contains information about a file containing a message attachment
/// stored as a temporary file.
///
/// The file can contain a static OLE object, an embedded OLE object, an embedded message,
/// and other types of files.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// Bitmask of attachment flags. Flags are MAPI_OLE and MAPI_OLE_STATIC.
///
/// If neither flag is set, the attachment is treated as a data file.
///

public uint flFlags = 0;

///
/// An integer used to indicate where in the message text to render the attachment.
///
/// Attachments replace the character found at a certain position in the message text.
/// That is, attachments replace the character in the MapiMessage structure field
/// lpszNoteText[nPosition]. A value of – 1 (0xFFFFFFFF) means the attachment position is
/// not indicated; the client application will have to provide a way for the user to
/// access the attachment.
///

public uint nPosition = 0xffffffff;

///
/// Pointer to the fully qualified path of the attached file.
///
/// This path should include the disk drive letter and directory name.
///

public string lpszPathName = string.Empty;

///
/// Pointer to the attachment filename seen by the recipient, which may differ from the filename in
/// the lpszPathName member if temporary files are being used.
///
/// If the lpszFileName member is empty or NULL, the filename from lpszPathName is used.
///

public string lpszFileName = string.Empty;

///
/// Pointer to the attachment file type, which can be represented with a MapiFileTagExt
/// structure.
///
/// A value of NULL indicates an unknown file type or a file type determined by the operating system.
///

public IntPtr lpFileType = IntPtr.Zero;
}

///
/// MapiFileTagExt structure specifies a message attachment's type at its creation
/// and its current form of encoding so that it can be restored to its original type at its destination.
///
/// A MapiFileTagExt structure defines the type of an attached file for purposes such as encoding and
/// decoding the file, choosing the correct application to launch when opening it, or any use that
/// requires full information regarding the file type.
///
/// Client applications can use information in the lpTag and lpEncoding
/// members of this structure to determine what to do with an attachment.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileTagExt
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// The size, in bytes, of the value defined by the lpTag member.
///

public uint cbTag = 0;

///
/// Pointer to an X.400 object identifier indicating the type of the attachment in its original form,
/// for example "Microsoft Excel worksheet".
///

public IntPtr lpTag = IntPtr.Zero;

///
/// The size, in bytes, of the value defined by the lpEncoding member.
///

public uint cbEncoding = 0;

///
/// Pointer to an X.400 object identifier indicating the form in which the attachment is currently
/// encoded, for example MacBinary, UUENCODE, or binary.
///

public IntPtr lpEncoding = IntPtr.Zero;
}

///
/// A MapiMessage structure contains information about a message.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// Pointer to the text string describing the message subject,
/// typically limited to 256 characters or less.
///
/// If this member is empty or NULL, the user has not entered subject text.
///

public string lpszSubject = string.Empty;

///
/// Pointer to a string containing the message text.
///
/// If this member is empty or NULL, there is no message text.
///

public string lpszNoteText = string.Empty;

///
/// Pointer to a string indicating a non-IPM type of message.
///
/// Client applications can select message types for their non-IPM messages.
///
/// Clients that only support IPM messages can ignore the lpszMessageType member
/// when reading messages and set it to empty or NULL when sending messages.
///

public string lpszMessageType = null;

///
/// Pointer to a string indicating the date when the message was received.
///
/// The format is YYYY/MM/DD HH:MM, using a 24-hour clock.
///

public string lpszDateReceived = DateTime.Now.ToString("yyyy/MM/dd hh:mm");

///
/// Pointer to a string identifying the conversation thread to which the message belongs.
///
/// Some messaging systems can ignore and not return this member.
///

public string lpszConversationID = string.Empty;

///
/// Bitmask of message status flags.
///
/// The flags are MAPI_RECEIPT_REQUESTED , MAPI_SENT,
/// and MAPI_UNREAD.
///

public uint flFlags = 0;

///
/// Pointer to a MapiRecipDesc structure containing information about the
/// sender of the message.
///

public IntPtr lpOriginator = IntPtr.Zero;

///
/// The number of message recipient structures in the array pointed to by the
/// lpRecips member.
///
/// A value of zero indicates no recipients are included.
///

public uint nRecipCount = 0;

///
/// Pointer to an array of MapiRecipDesc structures, each containing
/// information about a message recipient.
///

public IntPtr lpRecips = IntPtr.Zero;

///
/// The number of structures describing file attachments in the array pointed to by the
/// lpFiles member.
///
/// A value of zero indicates no file attachments are included.
///

public uint nFileCount = 0;

///
/// Pointer to an array of MapiFileDesc structures, each containing
/// information about a file attachment.
///

public IntPtr lpFiles = IntPtr.Zero;
}

///
/// A MapiRecipDesc structure contains information about a message sender or recipient.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
///
/// Reserved; must be zero.
///

public uint ulReserved= 0;

///
/// Contains a numeric value that indicates the type of recipient.
///
/// Possible values are:
///
/// Value Constant Meaning
///
/// 0 MAPI_ORIG Indicates the original sender of the message.
/// 1 MAPI_TO Indicates a primary message recipient.
/// 2 MAPI_CC Indicates a recipient of a message copy.
/// 3 MAPI_BCC Indicates a recipient of a blind copy.
///
///

public uint ulRecipClass= MAPI.MAPI_TO;

///
/// Pointer to the display name of the message recipient or sender.
///

public string lpszName = string.Empty;

///
/// Optional pointer to the recipient or sender's address; this address is provider-specific message
/// delivery data. Generally, the messaging system provides such addresses for inbound messages.
///
/// For outbound messages, the lpszAddress member can point to an address entered by the user for
/// a recipient not in an address book (that is, a custom recipient).
///
/// The format of an address pointed to by the lpszAddress member is [address type][e-mail address].
/// Examples of valid addresses are FAX:206-555-1212 and SMTP:M@X.COM.
///

public string lpszAddress = string.Empty;

///
/// The size, in bytes, of the entry identifier pointed to by the lpEntryID member.
///

public uint ulEIDSize = 0;

///
/// Pointer to an opaque entry identifier used by a messaging system service provider to identify the
/// message recipient. Entry identifiers have meaning only for the service provider;
/// client applications will not be able to decipher them. The messaging system uses this member
/// to return valid entry identifiers for all recipients or senders listed in the address book.
///

public IntPtr lpEntryID = IntPtr.Zero;
}



public class MAPI
{

[DllImport("MAPI32.DLL",EntryPoint = "MAPILogon", CharSet = CharSet.Ansi)]
public static extern UInt32 Logon(IntPtr ulUIParam, string lpszProfileName, string lpszPassword,
UInt32 flFlags, UInt32 ulReserved, ref IntPtr lplhSession);



[DllImport("MAPI32.DLL", EntryPoint = "MAPISendMail", CharSet = CharSet.Ansi)]
public static extern UInt32 SendMail(IntPtr lhSession, IntPtr ulUIParam,
MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);


[DllImport("MAPI32.DLL", EntryPoint = "MAPILogoff", CharSet = CharSet.Ansi)]
public static extern uint Logoff(IntPtr lhSession, IntPtr ulUIParam, uint flFlags, uint ulReserved);



public const int SUCCESS_SUCCESS = 0;
public const int MAPI_USER_ABORT = 1;
public const int MAPI_E_USER_ABORT = MAPI_USER_ABORT;
public const int MAPI_E_FAILURE = 2;
public const int MAPI_E_LOGIN_FAILURE = 3;
public const int MAPI_E_LOGON_FAILURE = MAPI_E_LOGIN_FAILURE;
public const int MAPI_E_DISK_FULL = 4;
public const int MAPI_E_INSUFFICIENT_MEMORY = 5;
public const int MAPI_E_BLK_TOO_SMALL = 6;
public const int MAPI_E_TOO_MANY_SESSIONS = 8;
public const int MAPI_E_TOO_MANY_FILES = 9;
public const int MAPI_E_TOO_MANY_RECIPIENTS = 10;
public const int MAPI_E_ATTACHMENT_NOT_FOUND = 11;
public const int MAPI_E_ATTACHMENT_OPEN_FAILURE = 12;
public const int MAPI_E_ATTACHMENT_WRITE_FAILURE = 13;
public const int MAPI_E_UNKNOWN_RECIPIENT = 14;
public const int MAPI_E_BAD_RECIPTYPE = 15;
public const int MAPI_E_NO_MESSAGES = 16;
public const int MAPI_E_INVALID_MESSAGE = 17;
public const int MAPI_E_TEXT_TOO_LARGE = 18;
public const int MAPI_E_INVALID_SESSION = 19;
public const int MAPI_E_TYPE_NOT_SUPPORTED = 20;
public const int MAPI_E_AMBIGUOUS_RECIPIENT = 21;
public const int MAPI_E_AMBIG_RECIP = MAPI_E_AMBIGUOUS_RECIPIENT;
public const int MAPI_E_MESSAGE_IN_USE = 22;
public const int MAPI_E_NETWORK_FAILURE = 23;
public const int MAPI_E_INVALID_EDITFIELDS = 24;
public const int MAPI_E_INVALID_RECIPS = 25;
public const int MAPI_E_NOT_SUPPORTED = 26;
public const int MAPI_ORIG = 0;
public const int MAPI_TO = 1;
public const int MAPI_CC = 2;
public const int MAPI_BCC = 3;
//***********************
// FLAG Declarations
//***********************
//* MAPILogon() flags *
public const int MAPI_LOGON_UI = 0x1;
public const int MAPI_NEW_SESSION = 0x2;
public const int MAPI_FORCE_DOWNLOAD = 0x1000;
//* MAPILogoff() flags *
public const int MAPI_LOGOFF_SHARED = 0x1;
public const int MAPI_LOGOFF_UI = 0x2;
//* MAPISendMail() flags *
public const int MAPI_DIALOG = 0x8;
//* MAPIFindNext() flags *
public const int MAPI_UNREAD_ONLY = 0x20;
public const int MAPI_GUARANTEE_FIFO = 0x100;
//* MAPIReadMail() flags *
public const int MAPI_ENVELOPE_ONLY = 0x40;
public const int MAPI_PEEK = 0x80;
public const int MAPI_BODY_AS_FILE = 0x200;
public const int MAPI_SUPPRESS_ATTACH = 0x800;
//* MAPIDetails() flags *
public const int MAPI_AB_NOMODIFY = 0x400;
//* Attachment flags *
public const int MAPI_OLE = 0x1;
public const int MAPI_OLE_STATIC = 0x2;
//* MapiMessage flags *
public const int MAPI_UNREAD = 0x1;
public const int MAPI_RECEIPT_REQUESTED = 0x2;
public const int MAPI_SENT = 0x4;

}


class Program
{
/*
public void SendMail()
{
uint ulResult = 0;
IntPtr hSession = IntPtr.Zero;
uint ulFlags = MAPI.MAPI_LOGON_UI | MAPI.MAPI_NEW_SESSION;

ulResult = MAPI.Logon(IntPtr.Zero, null, null, ulFlags, 0, ref hSession);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine(" MAPILogon() fn failed...");
return;
}



MapiRecipDesc recipient = new MapiRecipDesc();
recipient.Reserved = 0;
recipient.RecipClass = MAPI.MAPI_TO;
recipient.Name = null;
recipient.Address = "sundararajan_svks@yahoo.com";
recipient.EIDSize = 0;
recipient.EntryID = null;

MapiMessage message = new MapiMessage();
message.Reserved = 0;
message.Subject = "Greetings From C#";
message.NoteText = "Hello Mr...Sundara rajan";
message.MessageType = null;
message.DateReceived = null;
message.ConversationID = null;
message.Flags = 0;
message.Originator = null;
message.RecipCount = 1;
message.Recips = recipient;
message.FileCount = 0;
message.Files = null;


ulResult = MAPI.SendMail(hSession, IntPtr.Zero, ref message, MAPI.MAPI_NEW_SESSION, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("SendMail() fn failed...");
return;
}

ulResult = MAPI.Logoff(hSession, IntPtr.Zero, 0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("Logoff() fn failed...");
return;
}
}
*/

public void SendMail2()
{
uint ulResult = 0;
IntPtr hSession = IntPtr.Zero;
uint ulFlags = MAPI.MAPI_LOGON_UI | MAPI.MAPI_NEW_SESSION;

ulResult = MAPI.Logon(IntPtr.Zero, null, null, 0, 0, ref hSession);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine(" MAPILogon() fn failed...");
return;
}

MapiMessage message = new MapiMessage();
message.lpszSubject = "Greetings From C#";
message.lpszNoteText = "Hello Mr...Sundara rajan";
message.lpOriginator = IntPtr.Zero;//AllocOrigin();
message.nRecipCount = 1;
message.lpRecips = AllocRecips();

ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("SendMail() fn failed...");
return;
}

ulResult = MAPI.Logoff(hSession, IntPtr.Zero, 0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("Logoff() fn failed...");
return;
}

Marshal.FreeHGlobal(message.lpRecips);
}

private IntPtr AllocOrigin()
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.ulRecipClass = MAPI.MAPI_ORIG;
recipient.lpszName = "sundar";
recipient.lpszAddress = "sundararajan.svks@gmail.com";
recipient.ulEIDSize = 0;
recipient.lpEntryID = IntPtr.Zero;

Type rtype = typeof(MapiRecipDesc);
int rsize = Marshal.SizeOf(rtype);
IntPtr ptrr = Marshal.AllocHGlobal(rsize);

Marshal.StructureToPtr(recipient, ptrr, false);
return ptrr;

}
private IntPtr AllocRecips()
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.ulRecipClass = MAPI.MAPI_TO;
recipient.lpszName = "sundararajan";
recipient.lpszAddress = "sundararajan_svks@yahoo.com";
recipient.ulEIDSize = 0;
recipient.lpEntryID = IntPtr.Zero;

Type rtype = typeof(MapiRecipDesc);
int rsize = Marshal.SizeOf(rtype);
IntPtr ptrr = Marshal.AllocHGlobal(rsize);
Marshal.StructureToPtr(recipient, ptrr, false);
//Marshal.PtrToStructure(
return ptrr;


}
static void Main(string[] args)
{

Program p = new Program();
//p.SendMail();
p.SendMail2();
Console.ReadKey();
}
}
}

Labels:

MAPISendMail in C# Problem

ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,0, 0);

it works well But if i modified it as follows will not send mail...


ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,MAPI.MAPI_DIALOG, 0);

Labels:

Monday, August 06, 2007

C# 2.0 New features

C# 2.0 new features (.NET framework SDK):

1.Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are automatically generated.
2.Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.
3.Static classes that cannot be instantiated, and that only allow static members. This is similar to the concept of module in many procedural languages.
4.A new form of iterator that provides generator functionality, using a yield return construct similar to yield in Python.
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable GetEven(IEnumerable numbers)
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}

5.Anonymous delegates providing closure functionality.

public void Foo(object parameter)
{
// ...

ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{
// ...
}

// ...
});
}

6.Covariance and contravariance for signatures of delegates
7. The accessibility of property accessors can be set independently. Example:

string status = string.Empty;
public string Status
{
get { return status; } // anyone can get value of this property,
protected set { status = value; } // but only derived classes can change it
}

8.Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.
int? i = null;
object o = i;
if (o == null) Console.WriteLine("Correct behaviour - you have a runtime version from September 2005 or later");
else Console.WriteLine("Incorrect behaviour - you are running a pre-release runtime (from before September)");
When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal.
9. Coalesce operator: (??) returns the first of its operands which is not null
object nullObj = null;
object obj = new Object();
return nullObj ?? obj; // returns obj

The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:

int? i = null;
int j = i ?? 0; // Unless i is null, initialize j to i. Else (if i is null), initialize j to 0.

Labels: ,

Wednesday, July 25, 2007

C# Tips

1.How to Write debug string in C# ?

Using System.Diagnostics.Debug.Writeline() fn, we can write the debug string

2.How do we play default window sounds in C# ?
in .NET 2.0,

System.Media namespace is available. To play for example the classical beep sound, you could use the following code:

System.Media.SystemSounds.Beep.Play();
Similarly, you could play the “Question” sound with this code:
System.Media.SystemSounds.Question.Play();
The System.Media namespace is defined in System.dll, so there are no new DLLs you would need to add to your project’s references to use the above code.
3.What does the /target: command line option do in the C# compiler?
All the /target: options except module create .NET assemblies. Depending on the option, the compiler adds metadata for the operating system to use when loading the portable executable (PE) file and for the runtime to use in executing the contained assembly or module.
module creates a module. The metadata in the PE does not include a manifest. Module/s + manifest make an assembly - the smallest unit of deployment. Without the metadata in the manifest, there is little the runtime can do with a module.
library creates an assembly without an entry point, by setting the EntryPointToken of the PE's CLR header to 0. If you look at the IL, it does not contain the .entrypoint clause. The runtime cannot start an application if the assembly does not have an entry point.
exe creates an assembly with an entry point, but sets the Subsystem field of the PE header to 3 (Image runs in the Windows character subsystem - see the _IMAGE_OPTIONAL_HEADER structure in winnt.h). If you ILDASM the PE, you will see this as .subsystem 0x0003. The OS launches this as a console app.
winexe sets the Subsystem field to 2. (Image runs in the Windows GUI subsystem). The OS launches this as a GUI app.


4.What is the difference between const and static readonly?
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
In the static readonly case, the containing class is allowed to modify it only
in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
class Program
{
public static readonly Test test = new Test();
static void Main(string[] args)
{
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
}
}
class Test
{
public string Name;
}
On the other hand, if Test were a value type, then assignment to test.Name would be an error.

5.How do I get and set Environment variables?
Use the System.Environment class.Specifically the GetEnvironmentVariable and SetEnvironmentVariable methods.Admitedly, this is not a question specific to C#, but it is one I have seen enough C# programmers ask, and the ability to set environment variables is new to the Whidbey release, as is the EnvironmentVariableTarget enumeration which lets you separately specify process, machine, and user.
Brad Abrams blogged on this way back at the start of this year, and followed up with a solution for pre-Whidbey users.


6.Preprocess Win32 Messages through Windows Forms
In the unmanaged world, it was quite common to intercept Win32 messages as they were plucked off the message queue. In that rare case in which you wish to do so from a managed Windows Forms application, your first step is to build a helper class which implements the IMessageFilter interface. The sole method, PreFilterMessage(), allows you to get at the underlying message ID, as well as the raw WPARAM and LPARAM data. By way of a simple example:
public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Intercept the left mouse button down message.
if (m.Msg == 513)
{
MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
return true;
}
return false;
}
}
At this point you must register your helper class with the Application type:
public class mainForm : System.Windows.Forms.Form
{
private MyMessageFilter msgFliter = new MyMessageFilter();

public mainForm()
{
// Register message filter.
Application.AddMessageFilter(msgFliter);
}

}
At this point, your custom filter will be automatically consulted before the message makes its way to the registered event hander. Removing the filter can be accomplished using the (aptly named) static Application.RemoveMessageFilter() method.


7.Be aware of Wincv.exe :


When you install the .NET SDK / VS.NET, you are provided with numerous stand alone programming tools, one of which is named wincv.exe (Windows Class Viewer). Many developers are unaware of wincv.exe, as it is buried away under the C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin subdirectory (by default).
This tool allows you to type in the name of a given type in the base class libraries and view the C# definition of the type. Mind you, wincv.exe will not show you the implementation logic, but you will be provided with a clean snapshot of the member definitions.


8.What is the equivalent to regsvr32 in .NET?
Where you once used Regsvr32 on unmanaged COM libraries, you will now use Regasm on managed .NET libraries.
“Regsvr32 is the command-line tool that registers .dll files as command components in the registry“
“Regasm.exe, the Assembly Registration tool that comes with the .NET SDK, reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently. Once a class is registered, any COM client can use it as though the class were a COM class. The class is registered only once, when the assembly is installed. Instances of classes within the assembly cannot be created from COM until they are actually registered.“ If you want to register an assembly programmatically, see the RegistrationServices class and ComRegisterFunctionAttribute

Labels: