2010-08-10 35 views

Trả lời

16

Trong khi tôi sẽ thường không đề nghị giảm xuống mức thấp Windows API, và điều này có thể không phải là cách duy nhất để làm điều này, nó làm các trick:

using System; 
using System.Windows.Forms; 

public class ClipboardEventArgs : EventArgs 
{ 
    public string ClipboardText { get; set; } 
    public ClipboardEventArgs(string clipboardText) 
    { 
     ClipboardText = clipboardText; 
    } 
} 

class MyTextBox : TextBox 
{ 
    public event EventHandler<ClipboardEventArgs> Pasted; 

    private const int WM_PASTE = 0x0302; 
    protected override void WndProc(ref Message m) 
    { 
     if (m.Msg == WM_PASTE) 
     { 
      var evt = Pasted; 
      if (evt != null) 
      { 
       evt(this, new ClipboardEventArgs(Clipboard.GetText())); 
       // don't let the base control handle the event again 
       return; 
      } 
     } 

     base.WndProc(ref m); 
    } 
} 

static class Program 
{ 
    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 

     var tb = new MyTextBox(); 
     tb.Pasted += (sender, args) => MessageBox.Show("Pasted: " + args.ClipboardText); 

     var form = new Form(); 
     form.Controls.Add(tb); 

     Application.Run(form); 
    } 
} 

Cuối cùng bộ công cụ WinForms không phải là rất tốt . Nó là một wrapper mỏng-ish xung quanh Win32 và Common Controls. Nó cho thấy 80% API hữu ích nhất. 20% còn lại thường bị thiếu hoặc không bị phơi bày theo cách hiển nhiên. Tôi sẽ đề nghị di chuyển ra khỏi WinForms và WPF nếu có thể như WPF có vẻ là một khuôn khổ kiến ​​trúc tốt hơn cho NET GUI.

+0

cảm ơn, tôi vừa mới học được sth mới (không chỉ cách bắt "dán", mà còn thiếu một số từ doin) – David

+0

từ khóa sự kiện bị thiếu trên khai báo trường đã dán và tại sao bạn sử dụng biến cục bộ evt? – Maxence

+0

@Maxence, FTFY. – dahvyd

Các vấn đề liên quan