在 HtmlEditor WinForms 上拦截粘贴事件

发布于 2024-08-27 23:59:33 字数 621 浏览 5 评论 0原文

我在 Windows 窗体中使用 HtmlEditor 控件。

我从此页面获得了控件:

http://windowsclient.net/articles/htmleditor.aspx

我想通过允许用户从剪贴板粘贴图像来扩展控件功能。现在,您可以粘贴纯文本和格式化文本,但是当尝试粘贴图像时,它不会执行任何操作。

基本上我的想法是检测用户何时在编辑器上按 Ctrl+V,检查剪贴板中是否有图像,如果有图像,则将其手动插入到编辑器中。

这种方法的问题是我无法引发表单的 OnKeyDown 或 OnKeyPress 事件。

我已将表单上的 KeyPreview 属性设置为 true,但仍然没有引发事件。

我还尝试对表单和编辑器进行子类化(如此处所述)以拦截 WM_PASTE 消息,但它也没有被提升。

关于如何实现这一目标有什么想法吗?

多谢

I'm using a HtmlEditor control inside a Windows Form.

I got the control from this page:

http://windowsclient.net/articles/htmleditor.aspx

I want to extend the controls functionality by allowing the user to paste images from the clipboard. Right now you can paste plain and formatted text, but when trying to paste an image it does nothing.

Basically what I thought was to detect when the user presses Ctrl+V on the editor, check the clipboard for images and if there's an image, insert it manually to the editor.

The problem with this approach is that I cannot get the OnKeyDown or OnKeyPress events of the form to be raised.

I have the KeyPreview property set to true on the form, but still the events aren't raised.

I also tried to Subclass the form and the editor (as explained here) to intercept the WM_PASTE message, but it isn't raised either.

Any ideas on how to achieve this?

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

堇色安年 2024-09-03 23:59:33

我花了一整天的时间研究这个问题,终于找到了解决方案。尝试侦听 WM_PASTE 消息不起作用,因为 Ctrl-V 正在由底层 mshtml 控件进行预处理。您可以侦听 OnKeyDown/Up 等来捕获 Ctrl-V,但这不会阻止底层 Control 继续其默认的粘贴行为。我的解决方案是阻止 Ctrl-V 消息的预处理,然后实现我自己的粘贴行为。为了阻止控件预处理 CtrlV 消息,我必须对 AxWebBrowser 控件进行子类化,

public class DisabledPasteWebBrowser : AxWebBrowser
{
    const int WM_KEYDOWN = 0x100;
    const int CTRL_WPARAM = 0x11;
    const int VKEY_WPARAM = 0x56;

    Message prevMsg;
    public override bool PreProcessMessage(ref Message msg)
    {
        if (prevMsg.Msg == WM_KEYDOWN && prevMsg.WParam == new IntPtr(CTRL_WPARAM) && msg.Msg == WM_KEYDOWN && msg.WParam == new IntPtr(VKEY_WPARAM))
        {
            // Do not let this Control process Ctrl-V, we'll do it manually.
            HtmlEditorControl parentControl = this.Parent as HtmlEditorControl;
            if (parentControl != null)
            {
                parentControl.ExecuteCommandDocument("Paste");
            }
            return true;
        }
        prevMsg = msg;
        return base.PreProcessMessage(ref msg);
    }
}

这是我处理粘贴命令的自定义方法,您的方法可能会对剪贴板中的图像数据执行类似的操作。

    internal void ExecuteCommandDocument(string command, bool prompt)
    {
        try
        {
            // ensure command is a valid command and then enabled for the selection
            if (document.queryCommandSupported(command))
            {
                if (command == HTML_COMMAND_TEXT_PASTE && Clipboard.ContainsImage())
                {
                    // Save image to user temp dir
                    String imagePath = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + ".jpg";
                    Clipboard.GetImage().Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    // Insert image href in to html with temp path
                    Uri uri = null;
                    Uri.TryCreate(imagePath, UriKind.Absolute, out uri);
                    document.execCommand(HTML_COMMAND_INSERT_IMAGE, false, uri.ToString());
                    // Update pasted id
                    Guid elementId = Guid.NewGuid();
                    GetFirstControl().id = elementId.ToString();
                    // Fire event that image saved to any interested listeners who might want to save it elsewhere as well
                    if (OnImageInserted != null)
                    {
                        OnImageInserted(this, new ImageInsertEventArgs { HrefUrl = uri.ToString(), TempPath = imagePath, HtmlElementId = elementId.ToString() });
                    }
                }
                else
                {
                    // execute the given command
                    document.execCommand(command, prompt, null);
                }
            }
        }
        catch (Exception ex)
        {
            // Unknown error so inform user
            throw new HtmlEditorException("Unknown MSHTML Error.", command, ex);
        }

    }

希望有人觉得这很有帮助,并且不会像我今天一样在上面浪费一天的时间。

I spent all day on this problem and finally have a solution. Trying to listen for the WM_PASTE message doesn't work because Ctrl-V is being PreProcessed by the underlying mshtml Control. You can listen for OnKeyDown/Up etc to catch a Ctrl-V but this won't stop the underlying Control from proceeding with its default Paste behavior. My solution is to prevent the PreProcessing of the Ctrl-V message and then implementing my own Paste behavior. To stop the control from PreProcessing the CtrlV message I had to subclass my Control which is AxWebBrowser,

public class DisabledPasteWebBrowser : AxWebBrowser
{
    const int WM_KEYDOWN = 0x100;
    const int CTRL_WPARAM = 0x11;
    const int VKEY_WPARAM = 0x56;

    Message prevMsg;
    public override bool PreProcessMessage(ref Message msg)
    {
        if (prevMsg.Msg == WM_KEYDOWN && prevMsg.WParam == new IntPtr(CTRL_WPARAM) && msg.Msg == WM_KEYDOWN && msg.WParam == new IntPtr(VKEY_WPARAM))
        {
            // Do not let this Control process Ctrl-V, we'll do it manually.
            HtmlEditorControl parentControl = this.Parent as HtmlEditorControl;
            if (parentControl != null)
            {
                parentControl.ExecuteCommandDocument("Paste");
            }
            return true;
        }
        prevMsg = msg;
        return base.PreProcessMessage(ref msg);
    }
}

Here is my custom method to handle Paste commands, yours might do something similar with the Image data from the Clipboard.

    internal void ExecuteCommandDocument(string command, bool prompt)
    {
        try
        {
            // ensure command is a valid command and then enabled for the selection
            if (document.queryCommandSupported(command))
            {
                if (command == HTML_COMMAND_TEXT_PASTE && Clipboard.ContainsImage())
                {
                    // Save image to user temp dir
                    String imagePath = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + ".jpg";
                    Clipboard.GetImage().Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    // Insert image href in to html with temp path
                    Uri uri = null;
                    Uri.TryCreate(imagePath, UriKind.Absolute, out uri);
                    document.execCommand(HTML_COMMAND_INSERT_IMAGE, false, uri.ToString());
                    // Update pasted id
                    Guid elementId = Guid.NewGuid();
                    GetFirstControl().id = elementId.ToString();
                    // Fire event that image saved to any interested listeners who might want to save it elsewhere as well
                    if (OnImageInserted != null)
                    {
                        OnImageInserted(this, new ImageInsertEventArgs { HrefUrl = uri.ToString(), TempPath = imagePath, HtmlElementId = elementId.ToString() });
                    }
                }
                else
                {
                    // execute the given command
                    document.execCommand(command, prompt, null);
                }
            }
        }
        catch (Exception ex)
        {
            // Unknown error so inform user
            throw new HtmlEditorException("Unknown MSHTML Error.", command, ex);
        }

    }

Hope someone finds this helpful and doesn't waste a day on it like me today.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文