简体   繁体   中英

Share a string between methods in C#

Does anybody knows a way to share a string between methods in C#?

This is the piece of code where I need the get my string:

    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;

    }

In here in need the get the 'capture' string:

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

And place 'capture' from this method:

   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);
            }
        }

    }

In here:

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

I hope someone can help!

PS: If you don't understand the whole thing, I'm 14 and from the netherlands, So i'm not the best English writer :-).

You're looking at scope of variables.

Your variable capture is defined at the method level, and therefore only available that method.

You can define the variable at the class level (outside of the method) and all of the methods within your class will have access to it.

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);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM