本文實例為大家分享了winform可拖動的自定義label控件,供大家參考,具體內容如下
效果預覽:
實現步驟如下:
(1)首先在項目上右擊選擇:添加->新建項,添加自定義控件
(2)自定義的一個label讓它繼承labelcontrol控件,labelcontrol控件是devexpress控件庫里面的一種,和label控件差不多,想了解更多關于devexpress控件,推薦到devexpress控件論壇學習:
1
|
public partial class labelmodule : labelcontrol |
(3)這個label需要實現的mousedown。
1
2
3
4
5
6
7
|
private void labelmodule_mousedown( object sender, mouseeventargs e) { ismousedown = true ; mousepreposition = new point(e.x, e.y); this .borderstyle = devexpress.xtraeditors.controls.borderstyles.simple; this .cursor = cursors.sizeall; } |
(4)mouseup,也就是鼠標彈起的方法。
1
2
3
4
5
6
|
private void labelmodule_mouseup( object sender, mouseeventargs e) { ismousedown = false ; this .borderstyle = devexpress.xtraeditors.controls.borderstyles. default ; this .cursor = cursors. default ; } |
(5)mousemove,也就是鼠標移動時的方法。
1
2
3
4
5
6
|
private void labelmodule_mousemove( object sender, mouseeventargs e) { if (!ismousedown) return ; this .top = this .top + (e.y - mousepreposition.y); this .left = this .left + (e.x - mousepreposition.x); } |
e.x,e.y 指的是:鼠標的坐標因所引發的事件而異。例如,當處理 control.mousemove 事件時,鼠標的坐標值是相對于引發事件的控件的坐標。一些與拖放操作相關的事件具有相對于窗體原點或屏幕原點的關聯的鼠標坐標值。
完整代碼:labelmodule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using devexpress.xtraeditors; namespace ijprintersoftware { public partial class labelmodule : labelcontrol { private bool ismousedown = false ; private point mousepreposition; private void init() { initializecomponent(); this .mousedown += new mouseeventhandler(labelmodule_mousedown); this .mouseup += new mouseeventhandler(labelmodule_mouseup); this .mousemove+= new mouseeventhandler(labelmodule_mousemove); } public labelmodule() { init(); } private void labelmodule_mousedown( object sender, mouseeventargs e) { ismousedown = true ; mousepreposition = new point(e.x, e.y); this .borderstyle = devexpress.xtraeditors.controls.borderstyles.simple; this .cursor = cursors.sizeall; } private void labelmodule_mouseup( object sender, mouseeventargs e) { ismousedown = false ; this .borderstyle = devexpress.xtraeditors.controls.borderstyles. default ; this .cursor = cursors. default ; } private void labelmodule_mousemove( object sender, mouseeventargs e) { if (!ismousedown) return ; this .top = this .top + (e.y - mousepreposition.y); this .left = this .left + (e.x - mousepreposition.x); } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/a1061747415/article/details/47656307