You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Drafting Demo 2022.2中如何用Shift键强制光标水平移动?

实现Shift键强制水平绘制直线的方案

要在DrawInteractive模式下实现Shift键强制水平移动光标(即使起点不在网格上),可以通过监听键盘状态+约束鼠标坐标的方式实现,以下是具体代码实现步骤:


1. 定义状态变量

在你的MyDesign类中添加私有字段,用于跟踪Shift键状态和绘制起点:

private bool _isShiftPressed;
private Point _drawStartPoint = Point.Empty;

2. 监听键盘按键事件

重写OnKeyDown和OnKeyUp方法,更新Shift键的状态:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.ShiftKey)
    {
        _isShiftPressed = true;
        if (CurrentDrawMode == DrawMode.Interactive)
        {
            Invalidate(); // 触发重绘,实时更新预览直线
        }
    }
}

protected override void OnKeyUp(KeyEventArgs e)
{
    base.OnKeyUp(e);
    if (e.KeyCode == Keys.ShiftKey)
    {
        _isShiftPressed = false;
        if (CurrentDrawMode == DrawMode.Interactive)
        {
            Invalidate();
        }
    }
}

3. 记录绘制起点

在鼠标按下开始绘制时,记录初始点击位置(不强制网格捕捉):

protected override void OnMouseDown(MouseEventArgs e)
{
    base.OnMouseDown(e);
    if (CurrentDrawMode == DrawMode.Interactive && e.Button == MouseButtons.Left)
    {
        _drawStartPoint = e.Location;
        // 初始化预览起点
        CurrentPreviewStartPoint = _drawStartPoint;
    }
}

4. 约束鼠标移动坐标

在OnMouseMove方法中,根据Shift键状态强制水平移动:

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    if (CurrentDrawMode != DrawMode.Interactive || _drawStartPoint == Point.Empty)
        return;

    Point targetPoint;
    if (_isShiftPressed)
    {
        // 强制水平移动:保持Y坐标与起点一致,X坐标跟随鼠标
        targetPoint = new Point(e.X, _drawStartPoint.Y);
    }
    else
    {
        // 原有网格捕捉逻辑(如果启用)
        targetPoint = GridSnapEnabled ? SnapToGrid(e.Location) : e.Location;
    }

    // 更新预览终点并触发重绘
    CurrentPreviewEndPoint = targetPoint;
    Invalidate();
}

补充说明

  • 如果需要同时支持水平/垂直切换(比如根据鼠标与起点的偏移量自动选择),可以修改约束逻辑:计算X和Y方向的偏移距离,选择偏移更大的方向进行约束
  • SnapToGrid是你原有网格捕捉的方法,需确保该方法能将坐标转换为最近的网格点
  • CurrentPreviewStartPoint/CurrentPreviewEndPoint是用于绘制预览直线的变量,需根据你的类结构调整命名

内容的提问来源于stack exchange,提问作者N.TW12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:57:11