VB.NET WinForms应用如何检测触摸屏初始触摸(手指按下)事件
在WinForms中捕获触摸按下事件(VB.NET)
方法一:使用控件的TouchDown事件
WinForms从.NET Framework 4.0开始原生支持触摸事件,Form、Panel、Button等多数控件都提供TouchDown事件,这就是你需要的手指按下屏幕时触发的事件。
如果之前没正确绑定或启用,可参考以下示例代码:
Public Class MainForm Private Sub MainForm_TouchDown(sender As Object, e As TouchEventArgs) Handles Me.TouchDown ' 手指按下时触发此逻辑 Dim touchPoint As TouchPoint = e.GetTouchPoint(Me) MessageBox.Show($"触摸按下,坐标:X={touchPoint.Location.X}, Y={touchPoint.Location.Y}") End Sub End Class
若事件未触发,检查几点:
- 项目目标框架需为.NET Framework 4.0或更高版本
- 确认触摸硬件驱动正常,系统已开启触摸支持
- 少数控件需设置
AllowDrop = True才能接收触摸事件
方法二:重写WndProc处理底层触摸消息
如果自定义控件或特殊场景下TouchDown事件失效,可直接处理Windows底层的WM_TOUCH消息(消息ID:0x0240),精准捕获触摸按下动作:
Public Class MainForm Private Const WM_TOUCH As Integer = &H240 Protected Overrides Sub WndProc(ByRef m As Message) MyBase.WndProc(m) If m.Msg = WM_TOUCH Then Dim inputCount As Integer = m.WParam.ToInt32() Dim touchInputs(inputCount - 1) As TOUCHINPUT Marshal.Copy(m.LParam, touchInputs, 0, inputCount) For Each input As TOUCHINPUT In touchInputs ' 判断是否为触摸按下动作(TOUCHEVENTF_DOWN = &H1) If (input.dwFlags And &H1) = &H1 Then ' 转换触摸坐标到窗体本地坐标系 Dim screenPoint As New Point(input.x \ 100, input.y \ 100) Dim clientPoint As Point = Me.PointToClient(screenPoint) MessageBox.Show($"触摸按下,坐标:X={clientPoint.X}, Y={clientPoint.Y}") End If Next ' 必须释放触摸输入句柄 CloseTouchInputHandle(m.LParam) End If End Sub ' 定义触摸输入结构体 <StructLayout(LayoutKind.Sequential)> Private Structure TOUCHINPUT Public x As Integer Public y As Integer Public hSource As IntPtr Public dwID As Integer Public dwFlags As Integer Public dwMask As Integer Public dwTime As Integer Public dwExtraInfo As IntPtr Public cxContact As Integer Public cyContact As Integer End Structure ' 导入Windows API函数 <DllImport("user32.dll")> Private Shared Function CloseTouchInputHandle(lParam As IntPtr) As Boolean End Function End Class
排查小贴士
- 若触摸事件仍无响应,检查系统触摸设置:确保触摸屏幕已启用,无其他软件拦截触摸输入
- 第三方控件需查看文档确认是否支持触摸,或通过
WndProc全局捕获触摸消息
内容的提问来源于stack exchange,提问作者jaume
相关产品推荐
相关产品推荐

