2010-04-09 140 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); 
     } 

    } 

希望有人認爲這有幫助,並且不會像今天一樣浪費我一天的時間。