2010-04-09 150 views
2

我在Windows窗体中使用HtmlEditor控件。拦截HtmlEditor上的粘贴事件WinForms

我从这个页面的控制:

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

我想通过允许用户从剪贴板粘贴图像扩展控制功能。现在你可以粘贴纯文本和格式化文本,但是当试图粘贴图像时,它什么都不做。

基本上我认为当用户在编辑器上按Ctrl + V时检测剪贴板上的图像,如果有图像,请手动将其插入编辑器。

这种方法的问题是我无法获取要引发的窗体的OnKeyDown或OnKeyPress事件。

我在表单上将KeyPreview属性设置为true,但仍然不会引发事件。

我也尝试子类的窗体和编辑器(如解释here)拦截WM_PASTE消息,但它也没有提出。

有关如何实现此目的的任何想法?

非常感谢

回答

5

我整天都在这个问题上,终于有一个解决方案。尝试监听WM_PASTE消息不起作用,因为Ctrl-V正在被基础mshtml控件预处理。您可以侦听OnKeyDown/Up等来捕获Ctrl-V,但这不会阻止基础控件继续使用其默认粘贴行为。我的解决方案是防止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); 
     } 

    } 

希望有人认为这有帮助,并且不会像今天一样浪费我一天的时间。