trvTreeView.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Drawing;
  6. using System.Drawing.Design;
  7. using System.Drawing.Drawing2D;
  8. using System.Runtime;
  9. using System.Windows.Forms;
  10. namespace Dongke.WinForm.Controls
  11. {
  12. internal partial class trvTreeView : TreeView, IDKControl, IAsyncControl
  13. {
  14. #region 构造函数
  15. public trvTreeView()
  16. {
  17. InitializeComponent();
  18. }
  19. public trvTreeView(IContainer container)
  20. {
  21. container.Add(this);
  22. InitializeComponent();
  23. }
  24. #endregion
  25. #region 成员变量
  26. private int indexUnchecked;
  27. private int indexChecked;
  28. private int indexIndeterminate;
  29. private bool useCustomImages;
  30. private bool useShowImage;
  31. #endregion
  32. #region 属性
  33. [Category("CheckState")]
  34. [DefaultValue(true)]
  35. public bool UseShowImage
  36. {
  37. get { return this.useShowImage; }
  38. set {this.useShowImage = value; }
  39. }
  40. [Category("CheckState")]
  41. [DefaultValue(false)]
  42. public bool UseCustomImages
  43. {
  44. get { return this.useCustomImages; }
  45. set { this.useCustomImages = value; }
  46. }
  47. [Category("CheckState")]
  48. [TypeConverter(typeof(TreeViewImageIndexConverter))]
  49. [Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
  50. [DefaultValue(0)]
  51. public int CheckedImageIndex
  52. {
  53. get
  54. {
  55. if (base.ImageList == null)
  56. return -1;
  57. if (this.indexChecked >= this.ImageList.Images.Count)
  58. return Math.Max(0, this.ImageList.Images.Count - 1);
  59. return this.indexChecked;
  60. }
  61. set
  62. {
  63. if (value == -1)
  64. value = 0;
  65. if (value < 0)
  66. throw new ArgumentException(string.Format("Index out of bounds! ({0}) index must be equal to or greater then {1}.", value.ToString(), "0"));
  67. if (this.indexChecked != value)
  68. {
  69. this.indexChecked = value;
  70. if (base.IsHandleCreated)
  71. base.RecreateHandle();
  72. }
  73. }
  74. }
  75. [Category("CheckState")]
  76. [TypeConverter(typeof(TreeViewImageIndexConverter))]
  77. [Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
  78. [DefaultValue(0)]
  79. public int UncheckedImageIndex
  80. {
  81. get
  82. {
  83. if (base.ImageList == null)
  84. return -1;
  85. if (this.indexUnchecked >= this.ImageList.Images.Count)
  86. return Math.Max(0, this.ImageList.Images.Count - 1);
  87. return this.indexUnchecked;
  88. }
  89. set
  90. {
  91. if (value == -1)
  92. value = 0;
  93. if (value < 0)
  94. throw new ArgumentException(string.Format("Index out of bounds! ({0}) index must be equal to or greater then {1}.", value.ToString(), "0"));
  95. if (this.indexUnchecked != value)
  96. {
  97. this.indexUnchecked = value;
  98. if (base.IsHandleCreated)
  99. base.RecreateHandle();
  100. }
  101. }
  102. }
  103. [Category("CheckState")]
  104. [TypeConverter(typeof(TreeViewImageIndexConverter))]
  105. [Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
  106. [DefaultValue(0)]
  107. public int IndeterminateImageIndex
  108. {
  109. get
  110. {
  111. if (base.ImageList == null)
  112. return -1;
  113. if (this.indexIndeterminate >= this.ImageList.Images.Count)
  114. return Math.Max(0, this.ImageList.Images.Count - 1);
  115. return this.indexIndeterminate;
  116. }
  117. set
  118. {
  119. if (value == -1)
  120. value = 0;
  121. if (value < 0)
  122. throw new ArgumentException(string.Format("Index out of bounds! ({0}) index must be equal to or greater then {1}.", value.ToString(), "0"));
  123. if (this.indexIndeterminate != value)
  124. {
  125. this.indexIndeterminate = value;
  126. if (base.IsHandleCreated)
  127. base.RecreateHandle();
  128. }
  129. }
  130. }
  131. #endregion
  132. #region 事件
  133. protected override void OnAfterCheck(TreeViewEventArgs e)
  134. {
  135. base.OnAfterCheck(e);
  136. TreeNode node = e.Node;
  137. if (node != null)
  138. {
  139. TriStateTreeNode clickedNode = node as TriStateTreeNode;
  140. if (clickedNode != null)
  141. {
  142. if (clickedNode.CheckboxVisible)
  143. {
  144. ToggleNodeState(clickedNode);
  145. }
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Paints the node specified.
  151. /// </summary>
  152. /// <param name="node"></param>
  153. /// <param name="gx"></param>
  154. private void PaintTreeNode(TriStateTreeNode node, Graphics gx)
  155. {
  156. if (this.CheckBoxes)
  157. {
  158. // calculate boundaries
  159. Rectangle ncRect = new Rectangle(node.Bounds.X - 35, node.Bounds.Y, 15, 15);
  160. // make sure the default checkboxes are gone
  161. ClearCheckbox(ncRect, gx);
  162. // draw lines, if we are supposed to
  163. if (this.ShowLines)
  164. {
  165. DrawNodeLines(node, ncRect, gx);
  166. }
  167. if (node.CheckboxVisible)
  168. {
  169. // now draw the checkboxes
  170. switch (node.CheckState)
  171. {
  172. case CheckState.Unchecked: // Normal
  173. DrawCheckbox(ncRect, gx, ButtonState.Normal | ButtonState.Flat);
  174. break;
  175. case CheckState.Checked: // Checked
  176. DrawCheckbox(ncRect, gx, ButtonState.Checked | ButtonState.Flat);
  177. break;
  178. case CheckState.Indeterminate: // Pushed
  179. DrawCheckbox(ncRect, gx, ButtonState.Pushed | ButtonState.Flat);
  180. break;
  181. }
  182. }
  183. }
  184. }
  185. /// <summary>
  186. /// Deletes the default checkboxes which are drawn when the treeview.Checkboxes property
  187. /// is set tot true.
  188. /// </summary>
  189. /// <param name="bounds"></param>
  190. /// <param name="gx"></param>
  191. private void ClearCheckbox(Rectangle bounds, Graphics gx)
  192. {
  193. // make sure the default checkboxes are gone.
  194. using (Brush brush = new SolidBrush(this.BackColor))
  195. {
  196. gx.FillRectangle(brush, bounds);
  197. }
  198. }
  199. /// <summary>
  200. /// Draws thee node lines before the checkboxes are drawn
  201. /// </summary>
  202. /// <param name="gx">Graphics context</param>
  203. private void DrawNodeLines(TriStateTreeNode node, Rectangle bounds, Graphics gx)
  204. {
  205. // determine type of line to draw
  206. NodeLineType lineType = node.NodeLineType;
  207. if (lineType == NodeLineType.None) { return; }
  208. using (Pen pen = new Pen(SystemColors.ControlDark, 1))
  209. {
  210. pen.DashStyle = DashStyle.Dot;
  211. gx.DrawLine(pen, new Point(bounds.X, bounds.Y + 8), new Point(bounds.X + 15, bounds.Y + 8));
  212. if (lineType == NodeLineType.WithChildren && node.IsExpanded)
  213. {
  214. gx.DrawLine(pen, new Point(bounds.X + 8, bounds.Y + 8), new Point(bounds.X + 8, bounds.Y + 16));
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// Draws a checkbox in the desired state and style
  220. /// </summary>
  221. /// <param name="bounds">boundaries of the checkbox</param>
  222. /// <param name="gx">graphics context object</param>
  223. /// <param name="buttonState">state to draw the checkbox in</param>
  224. private void DrawCheckbox(Rectangle bounds, Graphics gx, ButtonState buttonState)
  225. {
  226. // get the right image index
  227. //System.Windows.Forms.VisualStyles.CheckBoxState imageIndexss = System.Windows.Forms.VisualStyles.CheckBoxState.MixedPressed;
  228. //if ((buttonState & ButtonState.Normal) == ButtonState.Normal)
  229. // imageIndex = this.indexUnchecked;
  230. //if ((buttonState & ButtonState.Checked) == ButtonState.Checked)
  231. // imageIndex = this.indexChecked;
  232. //if ((buttonState & ButtonState.Pushed) == ButtonState.Pushed)
  233. // imageIndex = this.indexIndeterminate;
  234. // if we don't have custom images, or no imagelist, draw default images
  235. if (!this.useCustomImages || (this.useCustomImages && null == this.ImageList))
  236. {
  237. //ControlPaint.DrawMixedCheckBox(gx, bounds, buttonState);
  238. CheckBoxRenderer.DrawCheckBox(gx, bounds.Location, System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal);
  239. return;
  240. }
  241. // get the right image index
  242. int imageIndex = -1;
  243. if ((buttonState & ButtonState.Normal) == ButtonState.Normal)
  244. imageIndex = this.indexUnchecked;
  245. if ((buttonState & ButtonState.Checked) == ButtonState.Checked)
  246. imageIndex = this.indexChecked;
  247. if ((buttonState & ButtonState.Pushed) == ButtonState.Pushed)
  248. imageIndex = this.indexIndeterminate;
  249. if (imageIndex > -1 && imageIndex < this.ImageList.Images.Count)
  250. {
  251. // index is valid so draw the image
  252. this.ImageList.Draw(gx, bounds.X, bounds.Y, bounds.Width + 1, bounds.Height + 1, imageIndex);
  253. }
  254. else
  255. {
  256. // index is not valid so draw default image
  257. ControlPaint.DrawMixedCheckBox(gx, bounds, buttonState);
  258. }
  259. }
  260. /// <summary>
  261. /// Ovveride the WindowProcedure in order to intercept the itemdraw event
  262. /// </summary>
  263. /// <param name="m"></param>
  264. protected override void WndProc(ref Message m)
  265. {
  266. const int WM_NOTIFY = 0x4E;
  267. int iResult = 0;
  268. bool bHandled = false;
  269. if (m.Msg == (0x2000 | WM_NOTIFY))
  270. {
  271. if (m.WParam.Equals(this.Handle))
  272. {
  273. iResult = HandleNotify(m);
  274. m.Result = new IntPtr(iResult);
  275. bHandled = (iResult != 0);
  276. }
  277. }
  278. if (!bHandled)
  279. base.WndProc(ref m);
  280. }
  281. #endregion
  282. #region 私有方法
  283. /// <summary>
  284. /// Toggles node state between checked & unchecked
  285. /// </summary>
  286. /// <param name="node"></param>
  287. private void ToggleNodeState(TriStateTreeNode node)
  288. {
  289. // no need to toggle state for non-existing node ( or non-tristatetreenode! )
  290. if (null == node) return;
  291. // toggle state
  292. CheckState nextState;
  293. switch (node.CheckState)
  294. {
  295. case CheckState.Unchecked:
  296. nextState = CheckState.Checked;
  297. break;
  298. default:
  299. nextState = CheckState.Unchecked;
  300. break;
  301. }
  302. // notify the treeview that an update is about to take place
  303. BeginUpdate();
  304. // update the node state, and dependend nodes
  305. node.SetCheckedState(nextState);
  306. // force a redraw
  307. EndUpdate();
  308. }
  309. private int HandleNotify(Message msg)
  310. {
  311. const int NM_FIRST = 0;
  312. const int NM_CUSTOMDRAW = NM_FIRST - 12;
  313. // Drawstage
  314. const int CDDS_PREPAINT = 0x1;
  315. const int CDDS_POSTPAINT = 0x2;
  316. const int CDDS_ITEM = 0x10000;
  317. const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT);
  318. const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT);
  319. // Custom draw return flags
  320. const int CDRF_DODEFAULT = 0x0;
  321. const int CDRF_NOTIFYPOSTPAINT = 0x10;
  322. const int CDRF_NOTIFYITEMDRAW = 0x20;
  323. NMHDR tNMHDR;
  324. NMTVCUSTOMDRAW tNMTVCUSTOMDRAW;
  325. int iResult = 0;
  326. object obj;
  327. TreeNode node;
  328. TriStateTreeNode tsNode;
  329. try
  330. {
  331. if (!msg.LParam.Equals(IntPtr.Zero))
  332. {
  333. obj = msg.GetLParam(typeof(NMHDR));
  334. if (obj is NMHDR)
  335. {
  336. tNMHDR = (NMHDR)obj;
  337. if (tNMHDR.code == NM_CUSTOMDRAW)
  338. {
  339. obj = msg.GetLParam(typeof(NMTVCUSTOMDRAW));
  340. if (obj is NMTVCUSTOMDRAW)
  341. {
  342. tNMTVCUSTOMDRAW = (NMTVCUSTOMDRAW)obj;
  343. switch (tNMTVCUSTOMDRAW.nmcd.dwDrawStage)
  344. {
  345. case CDDS_PREPAINT:
  346. iResult = CDRF_NOTIFYITEMDRAW;
  347. break;
  348. case CDDS_ITEMPREPAINT:
  349. iResult = CDRF_NOTIFYPOSTPAINT;
  350. break;
  351. case CDDS_ITEMPOSTPAINT:
  352. node = TreeNode.FromHandle(this, tNMTVCUSTOMDRAW.nmcd.dwItemSpec);
  353. tsNode = node as TriStateTreeNode;
  354. if (tsNode != null)
  355. {
  356. Graphics graph = Graphics.FromHdc(tNMTVCUSTOMDRAW.nmcd.hdc);
  357. PaintTreeNode(tsNode, graph);
  358. graph.Dispose();
  359. }
  360. iResult = CDRF_DODEFAULT;
  361. break;
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. catch (Exception ex)
  369. {
  370. MessageBox.Show(ex.Message);
  371. }
  372. return iResult;
  373. }
  374. #endregion
  375. #region 结构
  376. private struct RECT
  377. {
  378. internal int left;
  379. internal int top;
  380. internal int right;
  381. internal int bottom;
  382. }
  383. private struct NMHDR
  384. {
  385. internal IntPtr hwndFrom;
  386. internal IntPtr idFrom;
  387. internal int code;
  388. }
  389. private struct NMCUSTOMDRAW
  390. {
  391. internal NMHDR hdr;
  392. internal int dwDrawStage;
  393. internal IntPtr hdc;
  394. internal RECT rc;
  395. internal IntPtr dwItemSpec;
  396. internal int uItemState;
  397. internal IntPtr lItemlParam;
  398. }
  399. private struct NMTVCUSTOMDRAW
  400. {
  401. internal NMCUSTOMDRAW nmcd;
  402. internal int clrText;
  403. internal int clrTextBk;
  404. internal int iLevel;
  405. }
  406. #endregion
  407. #region IAsyncControl 成员
  408. #region 成员变量
  409. /// <summary>
  410. /// 异步处理开始时,控件状态
  411. /// </summary>
  412. private bool _asyncBeginStatus = false;
  413. private bool _asyncBeginFocused = false;
  414. #endregion
  415. #region 公有方法
  416. /// <summary>
  417. /// 开始异步处理
  418. /// </summary>
  419. /// <param name="doFocus">是否处理焦点</param>
  420. public virtual void BeginAsync(ref bool doFocus)
  421. {
  422. if (doFocus && this.Focused)
  423. {
  424. this._asyncBeginFocused = true;
  425. doFocus = false;
  426. }
  427. this._asyncBeginStatus = this.Enabled;
  428. this.Enabled = false;
  429. }
  430. /// <summary>
  431. /// 结束异步处理
  432. /// </summary>
  433. public virtual void EndAsync()
  434. {
  435. this.Enabled = this._asyncBeginStatus;
  436. if (this._asyncBeginFocused)
  437. {
  438. this.Focus();
  439. }
  440. }
  441. #endregion
  442. #endregion
  443. }
  444. }