[英]Shift + mouse wheel horizontal scrolling
使用 shift + 滾輪在水平滾動中很常見。
這兩個都相當容易捕捉。 我可以使用帶有由 KeyDown、KeyUp 事件設置的標志的 MouseWheel 事件來跟蹤按下 shift 鍵的時間。
但是,我如何實際觸發水平滾動? 我知道 WM_MOUSEHWHEEL,可以用來觸發事件嗎?
更新:對於System.Windows.Form
有一個HScrollProperties
類型的HorizontalScroll
屬性。 您可以操作該對象上的Value
屬性來更改水平滾動條的位置。 但是,到目前為止,我還沒有發現該對象可用的任何其他控件。
如果您要創建自己的從UserControl
或ScrollControl
或Form
派生的UserControl
,您可以使用這個簡單的解決方案:
protected override void OnMouseWheel(MouseEventArgs e)
{
if (this.VScroll && (Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
this.VScroll = false;
base.OnMouseWheel(e);
this.VScroll = true;
}
else
{
base.OnMouseWheel(e);
}
}
如果控件具有AutoScroll
並顯示滾動條,當您滾動鼠標滾輪時,您將獲得以下行為:
注意到這種行為,我想出了這個 hack 來覆蓋控件的OnMouseWheel
,然后如果啟用垂直滾動條並按住 Shift ,它會在調用base.OnMouseWheel
之前禁用垂直滾動條。 這將欺騙控件滾動水平滾動條(如上所示的行為 3)。
在您的設計器文件中,您需要手動添加一個 MouseWheel 事件委托。
this.richTextBox.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.RichTextBox_MouseWheel);
然后,在后面的代碼中,您可以添加以下內容。
private const int WM_SCROLL = 276; // Horizontal scroll
private const int SB_LINELEFT = 0; // Scrolls one cell left
private const int SB_LINERIGHT = 1; // Scrolls one line right
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private void RichTextBox_MouseWheel(object sender, MouseEventArgs e)
{
if (ModifierKeys == Keys.Shift)
{
var direction = e.Delta > 0 ? SB_LINELEFT : SB_LINERIGHT;
SendMessage(this.richTextBox.Handle, WM_SCROLL, (IntPtr)direction, IntPtr.Zero);
}
}
有關 const 值的更多信息,請參閱以下 SO: 如何以編程方式滾動 winforms datagridview 控件?
如果可能,請使用Alvin 的解決方案。 好多了
與 VB.NET 中 xixonia 提供的代碼相同
Private Const WM_SCROLL As Integer = 276
Private Const SB_LINELEFT As Integer = 0
Private Const SB_LINERIGHT As Integer = 1
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(hWnd As IntPtr,
wMsg As UInteger,
wParam As IntPtr,
lParam As IntPtr) As Integer
End Function
Private Sub RichTextBox_MouseWheel(sender As Object, e As MouseEventArgs) Handles RichTextBox1.MouseWheel
If ModifierKeys = Keys.Shift Then
Dim direction = If(e.Delta > 0, SB_LINELEFT, SB_LINERIGHT)
SendMessage(Me.RichTextBox1.Handle, WM_SCROLL, CType(direction, IntPtr), IntPtr.Zero)
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.