在DataGridView中,按SHIFT和SPACE将默认选择整行.我发现的唯一解决方案(在
vb.net DataGridView – Replace Shortcut Key with typed character处引用)是关闭行选择功能.虽然这有效,但它并不理想,因为我仍然希望能够使用行选择器选择整行(例如,删除行),并通过将SelectionMode属性更改为除RowHeaderSelect以外的任何内容而失去该能力.有没有办法只捕获SHIFT SPACE组合并用简单的SPACE替换它?似乎没有任何关键事件甚至在控件的MutiSelect属性设置为True并且SelectionMode属性设置为RowHeaderSelect时识别出击键,因此我无法使用它们.
ETA:我想可能会关闭MultiSelect并将选择模式更改为CellSelect,然后为RowHeaderMouseClick事件添加事件处理程序将起作用… nope.
解决方法
我想出如何实现这一点的最好方法是从DataGridView继承并重写ProcessCmdKey方法.然后你可以拦截Shift Space并发送Space.只需将此类添加到项目中,并将所有DataGridViews切换到MyDataGridViews.我的解决方案从这个
DataGridView keydown event not working in C# SO问题(这也解释了为什么Zaggler的解决方案不起作用)和
SendKeys in ProcessCmdKey: change Shift-Space to just a Space Bytes.com帖子中汲取灵感.对不起,但它在C#中.
class MyDataGridView : System.Windows.Forms.DataGridView { protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg,System.Windows.Forms.Keys keyData) { if (keyData == (System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Shift)) { // DataGridView is dumb and will select a row when the user types Shift+Space // if you have the DGV set so that you can click a row header to select a row (for example,to delete the row) // this method will intercept Shift+Space and just send on Space so that the DGV properly handles this. // For example,if I type "ME TYPING IN ALL CAPS" it ends up looking like "METYPINGINALLCAPS". // Or if I type "Note: I have some OS thing to talk about" it looks like "Note:Ihave some OSthing to talk about" byte[] keyStates = new byte[255]; UnsafeNativeMethods.GetKeyboardState(keyStates); byte shiftKeyState = keyStates[16]; keyStates[16] = 0; // turn off the shift key UnsafeNativeMethods.SetKeyboardState(keyStates); System.Windows.Forms.SendKeys.SendWait(" "); keyStates[16] = shiftKeyState; // turn the shift key back on UnsafeNativeMethods.SetKeyboardState(keyStates); return true; } return base.ProcessCmdKey(ref msg,keyData); } [System.Security.SuppressUnmanagedCodeSecurity] internal static class UnsafeNativeMethods { [System.Runtime.InteropServices.DllImport("user32.dll",CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetKeyboardState(byte[] keystate); [System.Runtime.InteropServices.DllImport("user32.dll",CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int SetKeyboardState(byte[] keystate); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。