我也一直不明白.net cf下为什么要把这些功能给精简掉,最终 .net依然需要底层实现的功能,消息处理。无奈,我们需要自己实现,很多基本内容,比如子类化,快捷方式,比如文本框的点击事件,我们这里不介绍前几项,那不是重点。


首先,我们需要对textbox子类化,使用SetWindowLong将默认的消息处理注册到我们自己的一个函数,然后记录下返回值,返回值是表示原来函数的指针,然后在我们的函数中判断WM_LBUTTONDOWN消息的获得。
关键代码展示
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ClickableTextboxSample { public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region 子类化 [DllImport("coredll.dll")] private static extern int PostMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); [DllImport("coredll.dll")] private extern static int CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hwnd, uint msg, uint wParam, int lParam); [DllImport("coredll.dll")] public static extern IntPtr SetWindowLong(IntPtr hwnd, int nIndex, IntPtr dwNewLong); public const int GWL_WNDPROC = (-4); public IntPtr OldProc = IntPtr.Zero; public delegate int WndProcHandler(IntPtr hwnd, uint msg, uint wParam, int lParam); WndProcHandler myproc = null; #endregion //窗体创建好后执行 protected override void OnLoad(EventArgs e) { base.OnLoad(e); myproc = new WndProcHandler(MyWndProc); OldProc = SetWindowLong(textBox1.Handle, GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(myproc)); } public const int WM_LBUTTONUP = 0x202; int MyWndProc(IntPtr hwnd, uint msg, uint wParam, int lParam) { if (msg == WM_LBUTTONUP) { CallWindowProc(OldProc, hwnd, msg, wParam, lParam); KeyboardWindow key = new KeyboardWindow(); key.Input = textBox1.Text; if (key.ShowDialog() == DialogResult.OK) { textBox1.Text = key.Input; } return 1;//1表示处理过了,不需要系统继续处理了。 } return CallWindowProc(OldProc, hwnd, msg, wParam, lParam); } //本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/wuyazhe/archive/2010/07/05/5714741.aspx } }
范例工程下载地址:
本文介绍在.NET CF环境下如何通过子类化Textbox控件并重写其消息处理过程来响应鼠标左键抬起事件。通过使用P/Invoke调用Windows API函数,可以实现自定义的Textbox点击事件处理逻辑。
2127

被折叠的 条评论
为什么被折叠?



