2013-09-27 26 views
1

有沒有人知道在C#中的方法之間共享字符串的方法?在C#中的方法之間共享字符串

這是一段代碼,我需要讓我的字符串:

private void timer1_Tick(object sender, EventArgs e) 
    { 
     // The screenshot will be stored in this bitmap. 
     Bitmap capture = new Bitmap(screenBounds.Width, screenBounds.Height); 

     // The code below takes the screenshot and 
     // saves it in "capture" bitmap. 
     g = Graphics.FromImage(capture); 
     g.CopyFromScreen(Point.Empty, Point.Empty, screenBounds); 

     // This code assigns the screenshot 
     // to the Picturebox so that we can view it 
     pictureBox1.Image = capture; 

    } 

在這裏需要得到「捕獲」字符串:

 Bitmap capture = new Bitmap(screenBounds.Width, screenBounds.Height); 

,並把「捕獲」從這個方法:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (paint) 
     { 
      using (Graphics g = Graphics.FromImage(!!!Put Capture in Here!!!)) 
      { 
       color = new SolidBrush(Color.Black); 
       g.FillEllipse(color, e.X, e.Y, 5, 5); 
      } 
     } 

    } 

在這裏:

 using (Graphics g = Graphics.FromImage(!!!Put Capture in Here!!!)) 

我希望有人能幫忙! PS:如果你不明白整個事情,我是14歲,來自荷蘭,所以我不是最好的英文作家:-)。

+2

將位置'私有位圖捕獲;'在類內(而不是方法),然後使用'this.capture' /'capture'在每個函數內引用它。 –

+1

你已經使用'paint'作爲類字段。用'capture'做同樣的事情 –

回答

3

您正在查看範圍的變量。

您的變量capture在方法級別定義,因此僅適用於該方法。

您可以在類級別(方法外部)定義變量,並且類中的所有方法都可以訪問它。

Bitmap capture; 
private void timer1_Tick(object sender, EventArgs e) 
{ 
    // The screenshot will be stored in this bitmap. 
    capture = new Bitmap(screenBounds.Width, screenBounds.Height); 

    // The code below takes the screenshot and 
    // saves it in "capture" bitmap. 
    g = Graphics.FromImage(capture); 
    g.CopyFromScreen(Point.Empty, Point.Empty, screenBounds); 

    // This code assigns the screenshot 
    // to the Picturebox so that we can view it 
    pictureBox1.Image = capture; 

} 

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (paint) 
    { 
     using (Graphics g = Graphics.FromImage(capture)) 
     { 
      color = new SolidBrush(Color.Black); 
      g.FillEllipse(color, e.X, e.Y, 5, 5); 
     } 
    } 

} 
+2

當你完成它的時候一定要處理你的'Bitmap',否則當你用完GDI資源時你可能會遇到錯誤。 –

相關問題