Post by "xaep", 12-05-2006, 9:52
-----------------------------------------------------
Setting Margins
The margin message itself takes a single parameter with both left and right margin values combined into a single long value. The LoWord contains the left margin and the HiWord contains the right margin. This code demonstrates setting the Far margin for a TextBox with a given handle (setting the Near margin is a matter of reversing the margin flag and shift):
[DllImport("user32", CharSet=CharSet.Auto)]
private extern static int SendMessage(
IntPtr hwnd,
int wMsg,
int wParam,
int lParam);
private const int EC_LEFTMARGIN = 0x1;
private const int EC_RIGHTMARGIN = 0x2;
private const int EC_USEFONTINFO = 0xFFFF;
private const int EM_SETMARGINS = 0xD3;
private const int EM_GETMARGINS = 0xD4;
[DllImport("user32", CharSet=CharSet.Auto)]
private extern static int GetWindowLong(
IntPtr hWnd,
int dwStyle);
private const int GWL_EXSTYLE = (-20);
private const int WS_EX_RIGHT = 0x00001000;
private const int WS_EX_LEFT = 0x00000000;
private const int WS_EX_RTLREADING = 0x00002000;
private const int WS_EX_LTRREADING = 0x00000000;
private const int WS_EX_LEFTSCROLLBAR = 0x00004000;
private const int WS_EX_RIGHTSCROLLBAR = 0x00000000;
private static bool IsRightToLeft(IntPtr handle)
{
int style = GetWindowLong(handle, GWL_EXSTYLE);
return (
((style & WS_EX_RIGHT) == WS_EX_RIGHT) ||
((style & WS_EX_RTLREADING) == WS_EX_RTLREADING) ||
((style & WS_EX_LEFTSCROLLBAR) == WS_EX_LEFTSCROLLBAR));
}
private static void FarMargin(IntPtr handle, int margin)
{
int message = IsRightToLeft(handle) ? EC_LEFTMARGIN : EC_RIGHTMARGIN;
if (message == EC_LEFTMARGIN)
{
margin = margin & 0xFFFF;
}
else
{
margin = margin * 0x10000;
}
SendMessage(handle, EM_SETMARGINS, message, margin);
}
To make the class work with ComboBoxes, we need to be able to find the handle to the TextBox within the ComboBox. This is done using the Windows FindWindowsEx API call, using the class name of the TextBox (which is "EDIT"):
[DllImport("user32", CharSet=CharSet.Auto)]
private extern static IntPtr FindWindowEx(
IntPtr hwndParent,
IntPtr hwndChildAfter,
[MarshalAs(UnmanagedType.LPTStr)]
string lpszClass,
[MarshalAs(UnmanagedType.LPTStr)]
string lpszWindow);
///
/// Gets the handle of the TextBox contained within a
/// ComboBox control.
///
/// The ComboBox window handle.
/// The handle of the contained text box.
public static IntPtr ComboEdithWnd(IntPtr handle)
{
handle = FindWindowEx(handle, IntPtr.Zero, "EDIT", "\0");
return handle;
}
///
/// Sets the far margin of a TextBox control or the
/// TextBox contained within a ComboBox.
///
/// The Control to set the far margin
/// for
/// New far margin in pixels, or -1
/// to use the default far margin.
public static void FarMargin(Control ctl, int margin)
{
IntPtr handle = ctl.Handle;
if (typeof(System.Windows.Forms.ComboBox).IsAssignableFrom(ctl.GetType()))
{
handle = ComboEdithWnd(handle);
}
FarMargin(handle, margin);
} |