So I have a DateTimePicker and I want to set it to null when save it into a database, but by default it has the today's value. If I want to remove it and empty the DateTimePicker I am not able too.
I've tried to put it into the load form:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
It actually works, but if I want to set a date it will not display into the DateTimePicker. Do you have any idea how can I solve it?
I have once written a date time picker that accepts null values (and allows week numbers too, as a free bonus).
[DefaultEvent("ValueChanged")]
[ComVisible(true)]
[DefaultProperty("Value")]
[DefaultBindingProperty("Value")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[Designer("System.Windows.Forms.Design.DateTimePickerDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class NullableDateTimePicker : DateTimePicker
{
#region Externals
private const int GWL_STYLE = (-16);
private const int MCM_FIRST = 0x1000;
private const int MCM_GETMINREQRECT = (MCM_FIRST + 9);
private const int MCS_WEEKNUMBERS = 0x4;
private const int DTM_FIRST = 0x1000;
private const int DTM_GETMONTHCAL = (DTM_FIRST + 8);
[DllImport("User32.dll")]
public static extern int GetWindowLong(IntPtr h, int index);
[DllImport("User32.dll")]
public static extern int SetWindowLong(IntPtr h, int index, int value);
[DllImport("User32.dll")]
private static extern IntPtr SendMessage(IntPtr h, int msg, int param, int data);
[DllImport("User32.dll")]
private static extern int SendMessage(IntPtr h, int msg, int param, ref Rectangle data);
[DllImport("User32.dll")]
private static extern int MoveWindow(IntPtr h, int x, int y, int width, int height, bool repaint);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
private static extern IntPtr GetParent(IntPtr hWnd);
#endregion
#region General
public NullableDateTimePicker()
{
this.ShowCheckBox = true;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the date/time value assigned to the control.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The set value is less than System.Windows.Forms.DateTimePicker.MinDate or more than System.Windows.Forms.DateTimePicker.MaxDate.
/// </exception>
[RefreshProperties(RefreshProperties.All)]
[Bindable(true)]
public new DateTime? Value
{
get
{
if (!base.Checked)
{
return null;
}
return base.Value;
}
set
{
if (value.HasValue)
{
base.Checked = true;
if (this.Format == DateTimePickerFormat.Short)
{
base.Value = value.Value.Date;
}
else if (this.Format == DateTimePickerFormat.Time)
{
base.Value = default(DateTime).Add(value.Value.TimeOfDay);
}
else
{
base.Value = value.Value;
}
}
else
{
base.Checked = false;
}
}
}
/// <summary>
/// Gets or sets whether to show week numbers.
/// </summary>
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[DefaultValue(false)]
public bool ShowWeekNumbers
{
get;
set;
}
#endregion
#region Week numbers
/// <summary>
/// Raises the System.Windows.Forms.DateTimePicker.DropDown event.
/// </summary>
/// <param name="e">An System.EventArgs that contains the event data.</param>
protected override void OnDropDown(EventArgs e)
{
IntPtr monthView = SendMessage(this.Handle, DTM_GETMONTHCAL, 0, 0);
int style = GetWindowLong(monthView, GWL_STYLE);
if (this.ShowWeekNumbers)
{
style = style | MCS_WEEKNUMBERS;
}
else
{
style = style & ~MCS_WEEKNUMBERS;
}
Rectangle rect = new Rectangle();
SetWindowLong(monthView, GWL_STYLE, style);
SendMessage(monthView, MCM_GETMINREQRECT, 0, ref rect);
MoveWindow(monthView, 0, 0, rect.Right + 3, rect.Bottom, true);
//
// Resize the surrounding window to let the new text fit
//
IntPtr parent = GetParent(monthView);
Rectangle mainRect = new Rectangle();
SendMessage(parent, MCM_GETMINREQRECT, 0, ref mainRect);
MoveWindow(parent, 0, 0, mainRect.Right + 6, mainRect.Bottom + 6, true);
base.OnDropDown(e);
}
#endregion
}
It shows a checkbox to allow null values, and the new Value property allows null too, so it works from both the designer and code.
Related
I have a small desktop app where I'm using a mousehook to monitor a mouse click event inside and outside a window's form. So I want a Custom Control to raise an event whenever a mouse is click out of that control, but when the control itself clicked, or child controls within this custom control clicked, I want to ignore the event, or act differently.
The problem is all mousehooks I found so far, has no way of knowing the control window that is about to receive a click event.
I need to know which control window is about to receive the click event ahead of time, so that I can differentiate whether it is a child control of the Custom Control or any other control or outside of the form.
Here is the mousehook class I'm using. I found it online.
using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using Microsoft;
namespace library
{
/// <summary>
/// Abstract base class for Mouse and Keyboard hooks
/// </summary>
public abstract class GlobalHook
{
/// <summary>
///
/// </summary>
#region Windows API Code
[StructLayout(LayoutKind.Sequential)]
protected class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
protected class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
protected class MouseLLHookStruct
{
public POINT pt;
public int mouseData;
public int flags;
public int time;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
protected class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
protected static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
protected static extern int UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
protected static extern int CallNextHookEx(
int idHook,
int nCode,
IntPtr wParam,
IntPtr lParam);
[DllImport("user32")]
protected static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
[DllImport("user32")]
protected static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
protected static extern short GetKeyState(int vKey);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetThreadDesktop(uint dwThreadId);
protected delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
protected const int WH_MOUSE_LL = 14;
protected const int WH_KEYBOARD_LL = 13;
protected const int WH_MOUSE = 7;
protected const int WH_KEYBOARD = 2;
protected const int WM_MOUSEMOVE = 0x200;
protected const int WM_LBUTTONDOWN = 0x201;
protected const int WM_RBUTTONDOWN = 0x204;
protected const int WM_MBUTTONDOWN = 0x207;
protected const int WM_LBUTTONUP = 0x202;
protected const int WM_RBUTTONUP = 0x205;
protected const int WM_MBUTTONUP = 0x208;
protected const int WM_LBUTTONDBLCLK = 0x203;
protected const int WM_RBUTTONDBLCLK = 0x206;
protected const int WM_MBUTTONDBLCLK = 0x209;
protected const int WM_MOUSEWHEEL = 0x020A;
protected const int WM_KEYDOWN = 0x100;
protected const int WM_KEYUP = 0x101;
protected const int WM_SYSKEYDOWN = 0x104;
protected const int WM_SYSKEYUP = 0x105;
protected const byte VK_SHIFT = 0x10;
protected const byte VK_CAPITAL = 0x14;
protected const byte VK_NUMLOCK = 0x90;
protected const byte VK_LSHIFT = 0xA0;
protected const byte VK_RSHIFT = 0xA1;
protected const byte VK_LCONTROL = 0xA2;
protected const byte VK_RCONTROL = 0x3;
protected const byte VK_LALT = 0xA4;
protected const byte VK_RALT = 0xA5;
protected const byte LLKHF_ALTDOWN = 0x20;
#endregion
/// <summary>
///
/// </summary>
#region Private Variables
protected int _hookType;
protected int _handleToHook;
protected bool _isStarted;
protected HookProc _hookCallback;
#endregion
/// <summary>
///
/// </summary>
#region Properties
public bool IsStarted
{
///
get
{
return _isStarted;
}
}
#endregion
/// <summary>
///
/// </summary>
#region Constructor
public GlobalHook()
{
///
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
}
#endregion
/// <summary>
///
/// </summary>
#region Methods
public void Start()
{
///
if (!_isStarted && _hookType != 0)
{
// Make sure we keep a reference to this delegate!
// If not, GC randomly collects it, and a NullReference exception is thrown
_hookCallback = new HookProc(HookCallbackProcedure);
//
IntPtr pp = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
///
_handleToHook = SetWindowsHookEx(
_hookType,
_hookCallback,
(IntPtr)0/*Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0])*/,
/*0*/(int)GetThreadDesktop((uint)Thread.CurrentThread.ManagedThreadId));
/// Were we able to sucessfully start hook?
if (_handleToHook != 0)
{
///
_isStarted = true;
}
}
}
public void Stop()
{
///
if (_isStarted)
{
///
UnhookWindowsHookEx(_handleToHook);
///
_isStarted = false;
}
}
protected virtual int HookCallbackProcedure(int nCode, IntPtr wParam, IntPtr lParam)
{
// This method must be overriden by each extending hook
return 0;
}
protected void Application_ApplicationExit(object sender, EventArgs e)
{
///
if (_isStarted)
{
///
Stop();
}
}
#endregion
}
/// <summary>
/// Captures global mouse events
/// </summary>
public class MouseHook : GlobalHook
{
/// <summary>
///
/// </summary>
#region MouseEventType Enum
private enum MouseEventType
{
None,
MouseDown,
MouseUp,
DoubleClick,
MouseWheel,
MouseMove
}
#endregion
/// <summary>
///
/// </summary>
#region Events
public event MouseEventHandler MouseDown;
public event MouseEventHandler MouseUp;
public event MouseEventHandler MouseMove;
public event MouseEventHandler MouseWheel;
public event EventHandler Click;
public event EventHandler DoubleClick;
#endregion
/// <summary>
///
/// </summary>
#region Constructor
public MouseHook()
{
_hookType = WH_MOUSE_LL;
}
#endregion
/// <summary>
///
/// </summary>
#region Methods
protected override int HookCallbackProcedure(int nCode, IntPtr wParam, IntPtr lParam)
{
///
if (nCode > -1 && (MouseDown != null || MouseUp != null || MouseMove != null))
{
///
MouseLLHookStruct mouseHookStruct =
(MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
///
MouseButtons button = GetButton((Int32)wParam);
MouseEventType eventType = GetEventType((Int32)wParam);
///
MouseEventArgs e = new MouseEventArgs(
button,
(eventType == MouseEventType.DoubleClick ? 2 : 1),
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
(eventType == MouseEventType.MouseWheel ?
(short)((mouseHookStruct.mouseData >> 16) & 0xffff) : 0));
// Prevent multiple Right Click events (this probably happens for popup menus)
if (button == MouseButtons.Right && mouseHookStruct.flags != 0)
{
///
eventType = MouseEventType.None;
}
///
switch (eventType)
{
///
//Control cont = Control.FromHandle(wParam);
///
case MouseEventType.MouseDown:
///
if (MouseDown != null)
{
///
MouseDown(this, e);
}
break;
case MouseEventType.MouseUp:
if (Click != null)
{
///
Click(this, new EventArgs());
}
if (MouseUp != null)
{
///
MouseUp(this, e);
}
break;
case MouseEventType.DoubleClick:
if (DoubleClick != null)
{
///
DoubleClick(this, new EventArgs());
}
break;
case MouseEventType.MouseWheel:
if (MouseWheel != null)
{
///
MouseWheel(this, e);
}
break;
case MouseEventType.MouseMove:
if (MouseMove != null)
{
///
MouseMove(this, e);
}
break;
default:
break;
}
}
///
return CallNextHookEx(_handleToHook, nCode, wParam, lParam);
}
private MouseButtons GetButton(Int32 wParam)
{
///
switch (wParam)
{
///
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
return MouseButtons.Left;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_RBUTTONDBLCLK:
return MouseButtons.Right;
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MBUTTONDBLCLK:
return MouseButtons.Middle;
default:
return MouseButtons.None;
}
}
private MouseEventType GetEventType(Int32 wParam)
{
///
switch (wParam)
{
///
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
return MouseEventType.MouseDown;
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
return MouseEventType.MouseUp;
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
return MouseEventType.DoubleClick;
case WM_MOUSEWHEEL:
return MouseEventType.MouseWheel;
case WM_MOUSEMOVE:
return MouseEventType.MouseMove;
default:
return MouseEventType.None;
}
}
#endregion
}
}
I have the following class to Hide or Show all Taskbars. But I get only one handle and so only one taskbar is hidden.
public static class Taskbar
{
[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int command);
[DllImport("user32.dll")]
private static extern int FindWindowEx(int parent, int afterWindow, string className, string windowText);
private const int _SW_HIDE = 0;
private const int _SW_SHOW = 1;
/// <summary>
/// Show all taskbars
/// </summary>
public static void ShowAll()
{
int result = 0;
do
{
result = FindWindowEx(0, result, "Shell_TrayWnd", null);
ShowWindow(result, _SW_SHOW);
}
while (result != 0);
}
/// <summary>
/// Hide all taskbars
/// </summary>
public static void HideAll()
{
int result = 0;
do
{
result = FindWindowEx(0, result, "Shell_TrayWnd", null);
ShowWindow(result, _SW_HIDE);
}
while (result != 0);
}
}
I have used this snippet: https://stackoverflow.com/a/18257222/6229375
Do I have something wrong? I have 3 screens with 3 taskbars on windows 10.
I want to write a WPF application that docks to an application running in another process (this is a 3rd party app I have no control of). Ideally I would like to be able to define if the app docks on the left or right.
Here's an example of what I want to do:
I have tried to implement the following 2 examples with no success.
Attach window to window of another process - Button_Click gives the following error:
Attach form window to another window in C# - Button_Click_1 docks it the title bar but I cannot see the entire app:
The following is the code:
namespace WpfApplicationTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public static int GWL_STYLE = -16;
public static int WS_CHILD = 0x40000000;
[DllImport("user32")]
private static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int x,
int y,
int cx,
int cy,
uint uFlags);
private IntPtr _handle;
private void SetBounds(int left, int top, int width, int height)
{
if (_handle == IntPtr.Zero)
_handle = new WindowInteropHelper(this).Handle;
SetWindowPos(_handle, IntPtr.Zero, left, top, width, height, 0);
}
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Process hostProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
IntPtr hostHandle = hostProcess.MainWindowHandle;
//MyWindow window = new MyWindow();
this.ShowActivated = true;
HwndSourceParameters parameters = new HwndSourceParameters();
parameters.WindowStyle = 0x10000000 | 0x40000000;
parameters.SetPosition(0, 0);
parameters.SetSize((int)this.Width, (int)this.Height);
parameters.ParentWindow = hostHandle;
parameters.UsesPerPixelOpacity = true;
HwndSource src = new HwndSource(parameters);
src.CompositionTarget.BackgroundColor = Colors.Transparent;
src.RootVisual = (Visual)this.Content;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Process hostProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
if (hostProcess != null)
{
Hide();
//this.WindowStyle;
//new WindowInteropHelper(this).SetBounds(0, 0, 0, 0, BoundsSpecified.Location);
//SetWindowPos(new WindowInteropHelper(this).Handle, IntPtr.Zero, 0, 0, 0, 0, 0);
SetBounds(0, 0, 0, 0);
IntPtr hostHandle = hostProcess.MainWindowHandle;
IntPtr guestHandle = new WindowInteropHelper(this).Handle;
SetWindowLong(guestHandle, GWL_STYLE, GetWindowLong(guestHandle, GWL_STYLE) | WS_CHILD);
SetParent(guestHandle, hostHandle);
Show();
}
}
}
You implementation is totally wrong, you are trying to make your window as a child window of the window you want to snap to.
I wrote a small helper class for snapping to another window by it's title, I hope this helps.
WindowSnapper.cs
public class WindowSnapper
{
private struct Rect
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
public int Height
{
get { return Bottom - Top; }
}
public static bool operator !=(Rect r1, Rect r2)
{
return !(r1 == r2);
}
public static bool operator ==(Rect r1, Rect r2)
{
return r1.Left == r2.Left && r1.Right == r2.Right && r1.Top == r2.Top && r1.Bottom == r2.Bottom;
}
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
private DispatcherTimer _timer;
private IntPtr _windowHandle;
private Rect _lastBounds;
private Window _window;
private string _windowTitle;
public WindowSnapper(Window window, String windowTitle)
{
_window = window;
_window.Topmost = true;
_windowTitle = windowTitle;
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(10);
_timer.Tick += (x, y) => SnapToWindow();
_timer.IsEnabled = false;
}
public void Attach()
{
_windowHandle = GetWindowHandle(_windowTitle);
_timer.Start();
}
public void Detach()
{
_timer.Stop();
}
private void SnapToWindow()
{
var bounds = GetWindowBounds(_windowHandle);
if (bounds != _lastBounds)
{
_window.Top = bounds.Top;
_window.Left = bounds.Left - _window.Width;
_window.Height = bounds.Height;
_lastBounds = bounds;
}
}
private Rect GetWindowBounds(IntPtr handle)
{
Rect bounds = new Rect();
GetWindowRect(handle, ref bounds);
return bounds;
}
private IntPtr GetWindowHandle(string windowTitle)
{
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(windowTitle))
{
return pList.MainWindowHandle;
}
}
return IntPtr.Zero;
}
}
Usage example:
public partial class MainWindow : Window
{
private WindowSnapper _snapper;
public MainWindow()
{
InitializeComponent();
_snapper = new WindowSnapper(this, "Notepad");
_snapper.Attach();
}
}
I want remove CheckBoxes where the Node.Type is 5 or 6. I use this code:
private void TvOne_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
int type = (e.Node as Node).typ;
if (type == 5 || type == 6)
{
Color backColor, foreColor;
if ((e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected)
{
backColor = SystemColors.Highlight;
foreColor = SystemColors.HighlightText;
}
else if ((e.State & TreeNodeStates.Hot) == TreeNodeStates.Hot)
{
backColor = SystemColors.HotTrack;
foreColor = SystemColors.HighlightText;
}
else
{
backColor = e.Node.BackColor;
foreColor = e.Node.ForeColor;
}
using (SolidBrush brush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(brush, e.Node.Bounds);
}
TextRenderer.DrawText(e.Graphics, e.Node.Text, this.TvOne.Font,
e.Node.Bounds, foreColor, backColor);
if ((e.State & TreeNodeStates.Focused) == TreeNodeStates.Focused)
{
ControlPaint.DrawFocusRectangle(e.Graphics, e.Node.Bounds,
foreColor, backColor);
}
e.DrawDefault = false;
}
else
{
e.DrawDefault = true;
}
}
The Problem is that then the Image and the Line to the Root Node is not there.
How can Remove the Checkbox and let the Image and the Line there?
This is wrong!
In the code you've shown, you are handling the drawing yourself for all of the nodes whose type is either 5 or 6. For the rest of the types, you're simply allowing the system to draw the nodes in the default way. That's why they all have the lines as expected, but the ones you're owner-drawing do not: You forgot to draw in the lines! You see, when you say e.DrawDefault = false; it's assumed that you really do mean it. None of the regular drawing is done, including the standard lines.
You'll either need to draw in those lines yourself, or figure out how to get by without owner-drawing at all.
From the code you have now, it looks like you're trying to simulate the system's native drawing style as much as possible in your owner-draw code, so it's not clear to me what exactly you accomplish by owner-drawing in the first place. If you're just trying to keep checkboxes from showing up for type 5 and 6 nodes (which, like the lines, are simply not getting drawn because you aren't drawing them!), there's a simpler way to do that without involving owner drawing.
So, you ask, what is that simpler way to hide the checkboxes for individual nodes? Well, it turns out that the TreeView control itself actually supports this, but that functionality is not exposed in the .NET Framework. You need to P/Invoke and call the Windows API to get at it. Add the following code to your form class (make sure you've added a using declaration for System.Runtime.InteropServices):
private const int TVIF_STATE = 0x8;
private const int TVIS_STATEIMAGEMASK = 0xF000;
private const int TV_FIRST = 0x1100;
private const int TVM_SETITEM = TV_FIRST + 63;
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
public int mask;
public IntPtr hItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public int cchTextMax;
public int iImage;
public int iSelectedImage;
public int cChildren;
public IntPtr lParam;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
ref TVITEM lParam);
/// <summary>
/// Hides the checkbox for the specified node on a TreeView control.
/// </summary>
private void HideCheckBox(TreeView tvw, TreeNode node)
{
TVITEM tvi = new TVITEM();
tvi.hItem = node.Handle;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_STATEIMAGEMASK;
tvi.state = 0;
SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
}
All of the messy stuff at the top are your P/Invoke declarations. You need a handful of constants, the TVITEM structure that describes the attributes of a treeview item, and the SendMessage function. At the bottom is the function you'll actually call to do the deed (HideCheckBox). You simply pass in the TreeView control and the particular TreeNode item from which you want to remove the checkmark.
So you can remove the checkmarks from each of the child nodes to get something that looks like this:
Using TreeViewExtensions.
Usage sample:
private void MyForm_Load(object sender, EventArgs e)
{
this.treeview1.DrawMode = TreeViewDrawMode.OwnerDrawText;
this.treeview1.DrawNode += new DrawTreeNodeEventHandler(arbolDependencias_DrawNode);
}
void treeview1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
if (e.Node.Level == 1) e.Node.HideCheckBox();
e.DrawDefault = true;
}
Here is the answer's code as an Extension method, using this you can do:
public static class TreeViewExtensions
{
private const int TVIF_STATE = 0x8;
private const int TVIS_STATEIMAGEMASK = 0xF000;
private const int TV_FIRST = 0x1100;
private const int TVM_SETITEM = TV_FIRST + 63;
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
public int mask;
public IntPtr hItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public int cchTextMax;
public int iImage;
public int iSelectedImage;
public int cChildren;
public IntPtr lParam;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
ref TVITEM lParam);
/// <summary>
/// Hides the checkbox for the specified node on a TreeView control.
/// </summary>
public static void HideCheckBox(this TreeNode node)
{
TVITEM tvi = new TVITEM();
tvi.hItem = node.Handle;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_STATEIMAGEMASK;
tvi.state = 0;
SendMessage(node.TreeView.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
}
}
This is very good! The only modification I'd make is to pass only the TreeNode and not the TreeView to the HideCheckBox method. The TreeView can be retrieved from the TreeNode itself:
TreeView tvw = node.TreeView;
I have a form which has a Combo Box Control. I have selected the drop down style property to DropDown. I have also set the DropDown Width to 250. I have set the auto complete mode to suggest and the auto complete source to listitems. it works absolutely fine when i click on the drop down. but when i type in somethin, the auto complete mode activates a drop down which has a small width.
any help appreciate. i wanna know how to increase the width of the auto complete drop down via code so that the list items are viewed properly. I am using C#.
I had asked this a couple of months back but didn't get a proper answer. now the customer wants it bad :(
??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
/// <summary>
/// Represents an ComboBox with additional properties for setting the
/// size of the AutoComplete Drop-Down window.
/// </summary>
public class ComboBoxEx : ComboBox
{
private int acDropDownHeight = 106;
private int acDropDownWidth = 170;
//<EditorBrowsable(EditorBrowsableState.Always), _
[Browsable(true), Description("The width, in pixels, of the auto complete drop down box"), DefaultValue(170)]
public int AutoCompleteDropDownWidth
{
get { return acDropDownWidth; }
set { acDropDownWidth = value; }
}
//<EditorBrowsable(EditorBrowsableState.Always), _
[Browsable(true), Description("The height, in pixels, of the auto complete drop down box"), DefaultValue(106)]
public int AutoCompleteDropDownHeight
{
get { return acDropDownHeight; }
set { acDropDownHeight = value; }
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
ACWindow.RegisterOwner(this);
}
#region Nested type: ACWindow
/// <summary>
/// Provides an encapsulation of an Auto complete drop down window
/// handle and window proc.
/// </summary>
private class ACWindow : NativeWindow
{
private static readonly Dictionary<IntPtr, ACWindow> ACWindows;
#region "Win API Declarations"
private const UInt32 WM_WINDOWPOSCHANGED = 0x47;
private const UInt32 WM_NCDESTROY = 0x82;
private const UInt32 SWP_NOSIZE = 0x1;
private const UInt32 SWP_NOMOVE = 0x2;
private const UInt32 SWP_NOZORDER = 0x4;
private const UInt32 SWP_NOREDRAW = 0x8;
private const UInt32 SWP_NOACTIVATE = 0x10;
private const UInt32 GA_ROOT = 2;
private static readonly List<ComboBoxEx> owners;
[DllImport("user32.dll")]
private static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetAncestor(IntPtr hWnd, UInt32 gaFlags);
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern void GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy,
uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
#region Nested type: EnumThreadDelegate
private delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);
#endregion
#region Nested type: RECT
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public readonly int Left;
public readonly int Top;
public readonly int Right;
public readonly int Bottom;
public Point Location
{
get { return new Point(Left, Top); }
}
}
#endregion
#endregion
private ComboBoxEx owner;
static ACWindow()
{
ACWindows = new Dictionary<IntPtr, ACWindow>();
owners = new List<ComboBoxEx>();
}
/// <summary>
/// Creates a new ACWindow instance from a specific window handle.
/// </summary>
private ACWindow(IntPtr handle)
{
AssignHandle(handle);
}
/// <summary>
/// Registers a ComboBoxEx for adjusting the Complete Dropdown window size.
/// </summary>
public static void RegisterOwner(ComboBoxEx owner)
{
if ((owners.Contains(owner)))
{
return;
}
owners.Add(owner);
EnumThreadWindows(GetCurrentThreadId(), EnumThreadWindowCallback, IntPtr.Zero);
}
/// <summary>
/// This callback will receive the handle for each window that is
/// associated with the current thread. Here we match the drop down window name
/// to the drop down window name and assign the top window to the collection
/// of auto complete windows.
/// </summary>
private static bool EnumThreadWindowCallback(IntPtr hWnd, IntPtr lParam)
{
if ((GetClassName(hWnd) == "Auto-Suggest Dropdown"))
{
IntPtr handle = GetAncestor(hWnd, GA_ROOT);
if ((!ACWindows.ContainsKey(handle)))
{
ACWindows.Add(handle, new ACWindow(handle));
}
}
return true;
}
/// <summary>
/// Gets the class name for a specific window handle.
/// </summary>
private static string GetClassName(IntPtr hRef)
{
var lpClassName = new StringBuilder(256);
GetClassName(hRef, lpClassName, 256);
return lpClassName.ToString();
}
/// <summary>
/// Overrides the NativeWindow's WndProc to handle when the window
/// attributes changes.
/// </summary>
protected override void WndProc(ref Message m)
{
if ((m.Msg == WM_WINDOWPOSCHANGED))
{
// If the owner has not been set we need to find the ComboBoxEx that
// is associated with this dropdown window. We do it by checking if
// the upper-left location of the drop-down window is within the
// ComboxEx client rectangle.
if ((owner == null))
{
Rectangle ownerRect = default(Rectangle);
var acRect = new RECT();
foreach (ComboBoxEx cbo in owners)
{
GetWindowRect(Handle, ref acRect);
ownerRect = cbo.RectangleToScreen(cbo.ClientRectangle);
if ((ownerRect.Contains(acRect.Location)))
{
owner = cbo;
break; // TODO: might not be correct. Was : Exit For
}
}
owners.Remove(owner);
}
if (((owner != null)))
{
SetWindowPos(Handle, IntPtr.Zero, -5, 0, owner.AutoCompleteDropDownWidth,
owner.AutoCompleteDropDownHeight, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
if ((m.Msg == WM_NCDESTROY))
{
ACWindows.Remove(Handle);
}
base.WndProc(ref m);
}
}
#endregion
}
This is what I did and it actually works really well. Good to find an answer atlast :)
This answer is an addition to reggie's answer.
If you want the user to be able to resize the auto-complete dropdown, then add the following code inside the WndProc method:
private const int WM_SIZING = 0x214;
if (m.Msg == WM_SIZING) {
if (owner != null) {
RECT rr = (RECT) Marshal.PtrToStructure(m.LParam, typeof(RECT));
owner.acDropDownWidth = (rr.Right - rr.Left);
owner.acDropDownHeight = (rr.Bottom - rr.Top);
}
}
kind of a bad design decision to do that. Why not set it to a static large size to start with? You can always use one of the events to get the text width and then use that to set the combobox width. Possibly the onPaint? easier way might be to create your own combobox class that inherits from combo box and then override the methods to do this yourself.