14 Replies - 568 Views - Last Post: 14 July 2011 - 05:26 PM Rate Topic: -----

#1 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Accessing Controls in a class

Posted 11 July 2011 - 01:35 PM

I have a form named frmMainGame and it has a panel and a picture box i would like to access in a class file called Graphics.cs which handles all the 2d graphic processing. I'm use to vb.net where all I'd have to do is

frmMaingame.picscreen.width


and i'd have the controls width. I searched google and was able to make a public property. So i did but I'm not sure where to put it. Here is the property I have made.

        public Panel panel
        {
            get { return picGeneral; }
            set { picGeneral = value; }
        }

        public PictureBox pic
        {
            get { return picscreen; }
            set { picscreen = value; }
        }


would i put that in the code for the form or would i add that to my Graphics.cs file?

Is This A Good Question/Topic? 0
  • +

Replies To: Accessing Controls in a class

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 11 July 2011 - 01:38 PM

We have good tutorials for accesing 'a' from 'b' situations.

You can still do what you described from VB.NET, but honestly it is a really bad practice no matter which .NET language you are using.

We have had this come up a LOT in the last 48 hours.
Is it a new school year?


The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Separating data from GUI - PLUS - serializing the data to XML
Passing values between forms/classes
Was This Post Helpful? 0
  • +
  • -

#3 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 11 July 2011 - 01:44 PM

I've looked at some of them. Those links are what i found on google. I guess I'll just re-read some of them. See if i understand better.

Don't go to school. This is all self taught. I use to go for programming but dropped out do to personal issues.

This post has been edited by crzyone9584: 11 July 2011 - 01:45 PM

Was This Post Helpful? 1
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 11 July 2011 - 01:56 PM

View Postcrzyone9584, on 11 July 2011 - 02:44 PM, said:

Don't go to school. This is all self taught. I use to go for programming but dropped out do to personal issues.


I couldn't agree with you more strongly.

I realize you have experience with VB, so don't read into any of this... Its just a but of resources I give to C# newbies. Maybe some if it will be useful to you in your transition.


Standard resources, references and suggestions for new programmers.


I would recommend you start with "Hello World" just like the other million+ coders out there. Then work your way up to the more advanced tasks like this.

The problem with taking on large, complex tasks like this when you are new to coding is that
  • it will frustrate you to the point of quitting,
  • you don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.


I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book.

Free editions of Visual Studio 2010

May I suggest picking up a basic C# introductory book? There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.
Design patterns as diagrams

The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Separating data from GUI - PLUS - serializing the data to XML
Passing values between forms/classes

Working with environmental variables
'Why do we use delegates?' thread

Debugging tutorial
Debugging tips
Debugging in detail
Great debugging tips
It still doesn't work, article

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.

And everyone always wants to connect to a database, right out of the gate so
Database tutorials right here on DIC

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
  • Learn how to search the 'net for examples. How to do a good search that will get you targeted answers.

  • Try to avoid having work actually take place in GUI control event handlers. It is usually better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    btnSave(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    Form1_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    


I strongly suggest installing VMware or some other virtualization technology on your development PC so you can create a couple virtual computers for testing. This would allow you to debug and test inside: WinXP32, XP64, Vista, Win7x32, Win7x64... etc. without having to actually have 5 physical PC's. Visual Studio will let you send the debug directly into one of these virtual machines so you can watch it operate, check its variables, see the crashes and so on just as if it were debugging on your real machine.
Was This Post Helpful? 0
  • +
  • -

#5 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 11 July 2011 - 02:02 PM

Thats the third time I've seen that post... Do you just have it saved in a notpad or something?
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 11 July 2011 - 02:09 PM

Yes. We get lots of students/newbies who ask the same things. I try to direct them to the best sources for *learning* instead of just copy/pasting someone else's code without comprehension.

Although there is a stickied post, anyone so new as to need it is also so new as to never search or read pre-existing posts and tutorials.
Was This Post Helpful? 0
  • +
  • -

#7 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 11 July 2011 - 04:27 PM

Well thanks for the help. Still a little lost, but im sure one of these links you supplied should work out.
Was This Post Helpful? 0
  • +
  • -

#8 Curtis Rutland  Icon User is online

  • (╯°□°)╯︵ (~ .o.)~
  • member icon


Reputation: 3831
  • View blog
  • Posts: 6,476
  • Joined: 08-June 10

Re: Accessing Controls in a class

Posted 11 July 2011 - 09:33 PM

The two that might be most useful to you for this specific task is the "Passing values between forms/classes" and the "Separating data from guis" tutorials. Actually, read that second one first. Those two cover what you need to know to do this.
Was This Post Helpful? 0
  • +
  • -

#9 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 14 July 2011 - 01:29 PM

Thanks Curtis. Saves me a bunch of time of reading a lot of things i don't need to.

I hope i understand how the Separating Data From GUI code is working. Hope someone could clarify if i don't.

First make a property in the class file like so.

public Panel Panel
{
    get; set; 
}


Then in my form I also make...

    private Graphics myGraphics = new Graphics(); // Empty but not a null that will raise an exception

    public Graphics gfx
    {
        get { return myGraphics; }
        set { myGraphics = value; }
    }


Then make the properties from there. But I don't see how i can get the width of the panel I'm trying to access. The tutorials is pretty much saying how to set the text and how to update the text boxes. I want to get the width and other properties of the panel I'm trying to draw some graphics on.

This post has been edited by crzyone9584: 14 July 2011 - 02:06 PM

Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 14 July 2011 - 02:23 PM

I'm lost as to how you are relating your drawing to the separation of data. There's no 'data' in any of that, like the data of a User's name.

Drawing is all GUI. There's no data to separate from that.

Also just making a new Graphics() won't help you. You need to get a Graphics context from the object you are trying to draw on. That's why we do all that work inside the OnPaint method, because it gives us that context.

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e); // Let everything else paint including the recent picture
            PaintCrosshairs();
        }

//pbDisplayWindow is the picturebox we're drawing on
//Notice how we don't hardcode any sizes.
// we compute off the existing size so it
// will dynamically adjust
        void PaintCrosshairs()
        {
            using (Graphics graph = this.pbDisplaywindow.CreateGraphics())
            {
                using (Pen penCurrent = new Pen(Color.GreenYellow, 3))
                {
                    #region Virticle line
                    var start = new Point
                                    {
                                        X = (pbDisplaywindow.Bounds.Right - pbDisplaywindow.Bounds.Left) / 2,
                                        Y = 0 // top of pbDisplayWindows
                                    };
                    var end = new Point
                                  {
                                      X = start.X,
                                      Y = pbDisplaywindow.Bounds.Bottom
                                  };

                    graph.DrawLine(penCurrent, start, end);
                    #endregion

                    #region Horizontal line
                    start = new Point
                                {
                                    Y = (pbDisplaywindow.Bounds.Bottom - pbDisplaywindow.Bounds.Top) / 2,
                                    X = 0 // Left of pbDisplayWindows
                                };
                    end = new Point
                              {
                                  Y = start.Y,
                                  X = pbDisplaywindow.Bounds.Right
                              };

                    graph.DrawLine(penCurrent, start, end);
                    #endregion
                }
                graph.Save();
            }
        }



Was This Post Helpful? 0
  • +
  • -

#11 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 14 July 2011 - 02:31 PM

I guess i asked the question wrong. I'm setting a bitmap in my graphics class to the width and hieght of my panel that is in my frmMainGame. problem is i cant access the width or height of the control do to it being a private control.

StatBarBackbuffer = new Bitmap(frmMainGame.picGeneral.Width, frmMainGame.picGeneral.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);


StatBarBackbuffer is used in something like the following.

public static void DrawStatsBars(this Graphics g)
        {
            g = Graphics.FromImage(Graphic.StatBarBackbuffer);
            Font fnt = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
            g.DrawImage(Graphic.EmptyHPBar, new Point(12, 12));
            g.DrawImage(Graphic.EmptyManaBar, new Point(12, 35));
            g.DrawImage(Graphic.EmptyEXPBar, new Point(12, 58));
            g.DrawImage(Graphic.HPBar, new Rectangle(12, 15, (int)JCIrrorgance.picHpWidth, Graphic.HPBar.Height), new Rectangle(0, 0, (int)JCIrrorgance.picHpWidth, Graphic.HPBar.Height), GraphicsUnit.Pixel);
            g.DrawImage(Graphic.ManaBar, new Rectangle(12, 38, (int)JCIrrorgance.picManaWidth, Graphic.ManaBar.Height), new Rectangle(0, 0, (int)JCIrrorgance.picManaWidth, Graphic.ManaBar.Height), GraphicsUnit.Pixel);
            g.DrawImage(Graphic.EXPBar, new Rectangle(12, 61, (int)JCIrrorgance.picEXPWidth, Graphic.EXPBar.Height), new Rectangle(0, 0, (int)JCIrrorgance.picEXPWidth, Graphic.EXPBar.Height), GraphicsUnit.Pixel);
            g.DrawString(JCIrrorgance.lblHPText, fnt, new SolidBrush(Color.Black), 40, 15);
            g.DrawString(JCIrrorgance.lblManaText, fnt, new SolidBrush(Color.Black), 40, 38);
            g.DrawString(JCIrrorgance.lblEXPText, fnt, new SolidBrush(Color.Black), 40, 63);
            g.Dispose();
            
            // g = frmMainGame.picGeneral.CreateGraphics;
            // g.DrawImage(Graphic.StatBarBackbuffer, new Point(0, 0));
            // g.Dispose();
        }


So my question is how do i get frmMainGame.picGeneral width from outside of the form?

EDIT: Also i never said anything about seperating data. I asked how i got a value from my form in a class file called Graphics. I re-read the first post. I asked the question correct. I'm not sure how we got to the separation of data.

This post has been edited by crzyone9584: 14 July 2011 - 02:45 PM

Was This Post Helpful? 0
  • +
  • -

#12 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 14 July 2011 - 02:54 PM

View Postcrzyone9584, on 14 July 2011 - 03:31 PM, said:

I guess i asked the question wrong. I'm setting a bitmap in my graphics class to the width and hieght of my panel that is in my frmMainGame. problem is i cant access the width or height of the control do to it being a private control.

StatBarBackbuffer = new Bitmap(frmMainGame.picGeneral.Width, frmMainGame.picGeneral.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);


Stop right there. The problem is that you are trying to have Form A directly change the GUI elements of Form B. Bad. Evil. Ptoohy.

Form A needs to raise an event saying... whatever... That the new score is 150,000.
Form B subscribes to that event then IT IS RESPONSIBLE FOR REPAINTING ITS OWN SELF with the new score.

Having 1 class/form trying to micromanage another is just wrong on so many levels we have multiple tutorials showing you how to do it right and verbally bashing on this type of tightly-bound relationship.

The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes

Do (not just 'read', but actually do and build the projects) for the first two lessons. That should set the concepts firmly in place in your mind. Then you can read in more detail the next couple lessons.
Was This Post Helpful? 0
  • +
  • -

#13 crzyone9584  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 198
  • Joined: 22-April 08

Re: Accessing Controls in a class

Posted 14 July 2011 - 04:30 PM

Your theory is wrong. You assumed i had two forms. I don't have two forms. I only have 1 form. So how will passing information between two forms work the same way as pulling information froma to a class file? I've been googling this subject for the past few days. Ever since i posted i had been doing research. Everything i found doesn't work. I even looked on msdn. They have the same thing form a and form b. and yet nothing works. Thanks for the help though.
Was This Post Helpful? 0
  • +
  • -

#14 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 1997
  • View blog
  • Posts: 8,808
  • Joined: 29-May 08

Re: Accessing Controls in a class

Posted 14 July 2011 - 04:47 PM

Beware that VB.net has (In my opinion a suck up to vb6 developers who refuse to change to .net practices.) of Default Instance of Forms, where a form can be referred to via its "name".


Form1.Text="Hello World" // Default Instance.

Dim f1 As New Form1
f1.Text="Hello World" 
 


Also a Form is no different to a Class, it still is one.

This post has been edited by AdamSpeight2008: 14 July 2011 - 04:49 PM

Was This Post Helpful? 0
  • +
  • -

#15 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 4963
  • View blog
  • Posts: 10,558
  • Joined: 02-June 10

Re: Accessing Controls in a class

Posted 14 July 2011 - 05:26 PM

View Postcrzyone9584, on 14 July 2011 - 05:30 PM, said:

Your theory is wrong. You assumed i had two forms. I don't have two forms. I only have 1 form. So how will passing information between two forms work the same way as pulling information froma to a class file? I've been googling this subject for the past few days. Ever since i posted i had been doing research. Everything i found doesn't work. I even looked on msdn. They have the same thing form a and form b. and yet nothing works. Thanks for the help though.


I assumed it based on your code
StatBarBackbuffer = new Bitmap(frmMainGame.picGeneral.Width, frmMainGame.picGeneral.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);


It looks very much like you are trying to reach into a form instance and get the width and height of a picturebox.

frmMainGame.picGeneral.Width, frmMainGame.picGeneral.Height

is frmMainGame an *INSTANCE* of a form, or is the form TYPE?
If you are trying to reference the type then you are way off.
If you are doing this from within the instance of your form as you seem to be saying

Quote

I only have 1 form

then you need to stop trying to reference a different form, or form type as n the above.
Just get the width and height of the picturebox on the form.

StatBarBackbuffer = new Bitmap(picGeneral.Width, picGeneral.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

Note we have taken out the references to frmMainGame
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1