2011-06-11 79 views
0

有人請告訴我一個如何基於圖片框創建自定義控件的例子嗎?自定義PictureBox控件

我只想這樣:如果圖片框被點擊(OnKeyDown),圖片應該向下移動3個像素,向右移動3px。之後在OnKeyUp事件我想恢復原始圖像。

有人能告訴我如何做到這一點?

+0

你在使用你的平臺? Silverlight的? WPF? asp.net?雙贏的形式?等你會得到更好的答案。 – 2011-06-11 15:43:29

+0

嗨,c#win-forms。 – nr1 2011-06-11 15:46:33

+0

我爲此解決方案添加了winforms標籤 – 2011-06-11 16:49:59

回答

2

「獲得點擊」是OnMouseX,而不是OnKeyX

public partial class UserControl1 : PictureBox 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    private bool shifted = false; 

    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left && this.Image != null) 
     { 
      this.shifted = true; 
      this.Invalidate(); 
     } 

     base.OnMouseDown(e); 
    } 

    protected override void OnMouseUp(MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left && this.Image != null) 
     { 
      this.shifted = false; 
      this.Invalidate(); 
     } 

     base.OnMouseUp(e); 
    } 

    protected override void OnPaint(PaintEventArgs pe) 
    { 
     if (this.shifted) 
     { 
      pe.Graphics.TranslateTransform(3, 3, System.Drawing.Drawing2D.MatrixOrder.Append); 
     } 

     base.OnPaint(pe); 
    } 
} 
+0

thx。只是一個問題:當點擊圖片框時,原始圖像以某種方式調整大小(=>很小)。 – nr1 2011-06-11 16:06:15

+0

@ nr1您可能會設置一個拉伸模式,在此示例中不會遵守這個模式。嘗試不拉伸。我只是在原則上展示如何做這種事情。您可以輕鬆添加對拉伸模式的支持。 – GSerg 2011-06-11 16:13:40

+0

@ nr1再想一想,我認爲最好是修改我的代碼。查看編輯。 – GSerg 2011-06-11 16:23:47

0

我知道這是一箇舊帖子,但我已經發現它,並且非常有用。 但我花了大約一個工作日的時間解決了我的DrawRectangle繪製在我加載的圖像下的問題。 解決方法是在OnPaint方法開始時移動base.OnPaint(pe);方法。

希望這會有所幫助。

亞當