c# - 如何修复此 Esc 键错误?

标签 c# winforms keyboard-shortcuts richtextbox runtime-error

我的记事本克隆程序中有这段代码,它用于跟踪我的 RichTextBox 中的克拉位置,并且对我来说运行良好。

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        Curpos();
    }

    private static int EM_LINEINDEX = 0xbb;
    [DllImport("user32.dll")]
    extern static int SendMessage(IntPtr hwnd, int message, int wparam, int lparam);

    private void Curpos()
    {
        {
            int line, col, index;
            index = richTextBox1.SelectionStart;
            line = richTextBox1.GetLineFromCharIndex(index);
            col = index - SendMessage(richTextBox1.Handle, EM_LINEINDEX, -1, 0);
            Lblcurpos.Text = "Line: " + (++line).ToString() + ", Column:"  + (++col).ToString();
        }
    }

它一直对我来说工作得很好,直到我添加了一些代码,以便我可以使用 Esc 键关闭我的程序。 这是我的 Esc 键的代码:

private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            this.Close();
        }
    }

编辑:这就是问题所在:

index = richTextBox1.SelectionStart;

当我这样做时,我可以很好地运行我的程序,在我的 RichTextBox 中键入文本以及所有内容,但是当我按 Esc 键时,它会显示:

Cannot Access disposed object Object name: 'RichTextBox'

然后是说:

Trouble Shooting Tips: Make sure you have not released a resource before attempting to use this. Get general help for this exception

关于我能做什么有什么想法吗?我尝试使用快捷键,但它没有可用于快捷键的 Esc 键。任何有关执行不同的快捷方式或解决此问题的帮助,我都会喜欢!!

最佳答案

尝试:

Application.Exit();

而不是

this.Close();

来自 MSDN:

Application.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

关于c# - 如何修复此 Esc 键错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17758075/

相关文章:

c# - 释放数据库操作使用的内存

vb.net - 使用 PrintDocument 和 HasMorePages 打印多页

javascript - 制作捕鼠器点击链接

javascript - 是否可以使用键盘在 JavaScript 中触发文件浏览器?

vim - ESC 在 cygwin vim 中不起作用

c# - 使用 Json.net 的 Instagram API

c# - 如何使用外键通过种子方法填充数据库并在 .NET C# EF 中创建表之间的关系?

c# - 不显示reportviewer直接打印RDLC Report

c# - 如何跳过数组中的前几个元素?

c# - BindingList 与我的类使用它的属性填充 ComboBox?