处理 TextBox 中的 OnKeyDown 后撤消缓冲区被清除 [英] Undo buffer getting cleared after handling OnKeyDown in TextBox

查看:24
本文介绍了处理 TextBox 中的 OnKeyDown 后撤消缓冲区被清除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在继承 TextBox:

I am subclassing TextBox:

class Editor : TextBox

我已经覆盖了 OnKeyDown,因为我想用四个空格替换制表符:

I have overridden OnKeyDown, because I want tabs to be replaced by four spaces:

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab) {
        SelectedText = "    ";
        e.SuppressKeyPress = true;
    }
}

这行得通,但不幸的是它也清除了撤消缓冲区.最终结果是,当用户按下 Tab 键时,Ctrl+Z 不起作用并且右键单击菜单上的撤消"被禁用.问题似乎是e.SuppressKeyPress = true;"部分.

This works, but unfortunately it also clears the undo buffer. The end result is that when the user presses tab, Ctrl+Z doesn't work and 'Undo' on the right-click menu becomes disabled. The problem appears to be the "e.SuppressKeyPress = true;" part.

有人知道如何解决这个问题吗?

Does anyone have any idea of how to get around this?

有关更多信息,我正在创建一个相当简单的文本编辑器,我不仅要处理 Tab 键(如上所述),还要处理 Enter 键.所以我对 Tab 和 Enter 有这个问题.我知道 RichTextBox 不存在此问题,但出于各种原因,我想改用 TextBox.

For more info, I am creating a fairly simple text editor, and I'm handling not only the Tab key (as above), but also the Enter key. So I have this problem with Tab and Enter. I am aware that this problem doesn't exist with RichTextBox, but for various reasons I want to use TextBox instead.

任何帮助将不胜感激,因为这是我项目中的一个显示问题.

Any help would be much appreciated, as this is a show-stopping problem in my project.

谢谢,汤姆

推荐答案

我终于找到了解决方案,就是使用Windows API如下:

I've finally found the solution, which is to use the Windows API as follows:

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab) {
        WinApi.SendMessage(Handle, WinApi.WmChar, WinApi.VkSpace, (IntPtr)4);
        e.SuppressKeyPress = true;
    }
    base.OnKeyDown(e);
}

这是我的 WinApi 类:

Here is my WinApi class:

using System;
using System.Runtime.InteropServices;

class WinApi
{ 
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    public const           UInt32 WmChar  =         0x102;
    public static readonly IntPtr VkSpace = (IntPtr)0x20;
}

这篇关于处理 TextBox 中的 OnKeyDown 后撤消缓冲区被清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆