C# :: Aufgabe #266

4 Lösungen Lösungen öffentlich

Flächenberechnung - Einstieg in Windows Forms

Anfänger - C# von paddlboot - 29.10.2019 um 11:12 Uhr
Erstelle ein Windows Forms Programm, in dem die Flächen von einem Dreieck und einem Rechteck berechnet werden können.

Die Eingben von Höhe und Breite sollen in einer Textbox erfolgen.
Nachdem auf einen Button (Rechteck, Dreieck, Beenden) geklickt wurde, soll das Ergebnis in einer Dritten Textbox ausgegeben werden, in welcher keine Eingaben gemacht werden können.
Bei Klicken des Beenden Buttons soll das Programm geschlossen werden.

Wie das ganze Aussehen könnte, sieht man in dem angehängten Screenshot.

Viel Spaß :)

Lösungen:

vote_ok
von Exception (7090 Punkte) - 31.10.2019 um 15:27 Uhr
Hinweise:
- Ungültiger Input wird abgefangen, das Textfeld wird rot markiert bis der Input valide ist.
- Es wird nach der Eingabe je nach gesetztem Modus (Rechteck, Dreieck) die Fläche berechnet. Dennoch ist es möglich die Fläche per Knopfdruck zu berechnen.

Form1.cs
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _266_Flaechenberechnung
{
    public partial class Form1 : Form
    {
        const string WIDTH = "Breite";
        const string HEIGHT = "Höhe";
        const string RESULT = "Ergebnis";
        const string RECTANGLE = "Rechteck";
        const string TRIANGLE = "Dreieck";
        const string EXIT = "Beenden";

        private Dictionary<string, System.Windows.Forms.Panel> panels;

        private double _widht;
        private double _height;
        private double _result;
        private string _mode;


        public Form1()
        {
            InitializeComponent();

            this._widht = 0.0;
            this._height = 0.0;
            this._result = 0.0;
            this._mode = "";

            this.InitForm();
        }

        private void InitForm()
        {
            this.Width = 500;
            this.Height = 500;

            this.panels = new Dictionary<string, Panel>();

            #region panels

            Panel pTop = new Panel();
            pTop.Name = "panel_top";
            pTop.Width = this.Width;
            pTop.Height = 100;
            pTop.Location = new Point(0, 0);
            //pTop.BackColor = Color.Green;
            this.panels.Add(pTop.Name, pTop);
            this.Controls.Add(pTop);

            Panel pLeft = new Panel();
            pLeft.Name = "panel_left";
            pLeft.Width = this.Width / 2;
            pLeft.Height = this.Height - pTop.Height * 2;
            pLeft.Location = new Point(0, pTop.Height);
            //pLeft.BackColor = Color.Red;
            this.panels.Add(pLeft.Name, pLeft);
            this.Controls.Add(pLeft);

            Panel pRight = new Panel();
            pRight.Name = "panel_right";
            pRight.Width = this.Width / 2;
            pRight.Height = this.Height - pTop.Height * 2;
            pRight.Location = new Point(pRight.Width, pTop.Height);
            //pRight.BackColor = Color.Blue;
            this.panels.Add(pRight.Name, pRight);
            this.Controls.Add(pRight);

            Panel pBottom = new Panel();
            pBottom.Name = "panel_bottom";
            pBottom.Width = this.Width;
            pBottom.Height = pTop.Height;
            pBottom.Location = new Point(0, pLeft.Bottom);
            //pBottom.BackColor = Color.Yellow;
            this.panels.Add(pBottom.Name, pBottom);
            this.Controls.Add(pBottom);

            #endregion

            #region Headline

            Label headline = new Label();
            headline.Text = "Flächenberechnung";
            headline.Width = pTop.Width / 2;
            headline.TextAlign = ContentAlignment.MiddleCenter;
            headline.Font = new Font(headline.Font.Name, 16, FontStyle.Underline);
            headline.Height = (int)headline.Font.Size * 2;
            headline.Location = new Point((this.Width / 2) - (headline.Width / 2), 10);
            pTop.Controls.Add(headline);

            #endregion

            #region description + input + buttons

            for (int i = 0; i < 3; i++)
            {
                string t = this.getTextByIndexAndType(i, new Label());

                Label description = new Label();
                description.Name = "label_" + t;
                description.Text = t;
                description.Width = pLeft.Width;
                description.Height = pLeft.Height / 3;
                description.TextAlign = ContentAlignment.MiddleCenter;
                description.Location = new Point(0, (pLeft.Height / 3) * i);
                pLeft.Controls.Add(description);

                TextBox input = new TextBox();
                input.Name = "input_" + t;
                input.Text = "";
                input.Width = pRight.Width - 50;
                double h = (pRight.Height / 3);
                input.Location = new Point(0, (int)(h * i) + (int)h / 2 - 5);

                if(t == Form1.RESULT)
                {
                    input.ReadOnly = true;
                }
                else
                {
                    input.KeyUp += CustomTextboxInputHandler;
                }

                pRight.Controls.Add(input);

                t = this.getTextByIndexAndType(i, new Button());

                Button b = new Button();
                b.Name = "button_" + t;
                b.Text = t;
                b.BackColor = Color.White;
                b.Width = pBottom.Width / 3 - 10;
                b.Height = pBottom.Height - 50;
                b.Location = new Point(b.Width * i + 5, 0);
                b.Click += CustomButtonHandler;
                pBottom.Controls.Add(b);
            }

            #endregion
        }

        private Control getControl(Panel p, string controlName, Type t)
        {
            var controls = p.Controls;

            foreach(Control c in controls)
            {
                if(c.Name == controlName)
                {
                    return c;
                }
            }

            return null;
        }

        private void CustomButtonHandler(object sender, EventArgs e)
        {
            Button b = sender as Button;

            string bName = b.Name.Replace("button_", "");

            if(bName == Form1.EXIT)
            {
                if(MessageBox.Show("Wirklich beenden?", "Beenden?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Application.Exit();
                }

                return;
            }

            // Farbe aller Buttons zurücksetzen
            var buttons = this.panels["panel_bottom"].Controls;

            foreach (Button tempButton in buttons)
            {
                tempButton.BackColor = Color.White;
            }

            b.BackColor = Color.LightGreen;
            this._mode = bName;

            if (this._mode != "")
            {
                this.CalcResult();
            }
        }

        private void CustomTextboxInputHandler(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;

            double result;

            if(Double.TryParse(t.Text, out result))
            {
                t.BackColor = Color.White;

                string tName = t.Name.Replace("input_", "");

                switch (tName)
                {
                    case Form1.WIDTH:
                        this._widht = result;
                        break;
                    case Form1.HEIGHT:
                        this._height = result;
                        break;
                    default:
                        break;
                }

                if(this._mode != "")
                {
                    this.CalcResult();
                }
            }
            else
            {
                t.BackColor = Color.LightPink; // Ungültiger Input markieren
            }
        }

        private void CalcResult()
        {
            TextBox tResult = this.getControl(this.panels["panel_right"], "input_Ergebnis", typeof(TextBox)) as TextBox;
            double result = 0.0;


            switch (this._mode)
            {
                case Form1.RECTANGLE:
                    result = this._widht * this._height;
                    break;
                case Form1.TRIANGLE:
                    result = 0.5 * this._widht * this._height;
                    break;
                default:
                    break;
            }

            tResult.Text = result.ToString();
        }

        private string getTextByIndexAndType(int i, object o)
        {
            if(o.GetType() == typeof(Label))
            {
                switch (i)
                {
                    case 0:
                        return Form1.WIDTH;
                    case 1:
                        return Form1.HEIGHT;
                    case 2:
                        return Form1.RESULT;
                    default:
                        return "";
                }
            }
            else if(o.GetType() == typeof(Button))
            {
                switch (i)
                {
                    case 0:
                        return Form1.RECTANGLE;
                    case 1:
                        return Form1.TRIANGLE;
                    case 2:
                        return Form1.EXIT;
                    default:
                        return "";
                }
            }
            else
            {
                return "";
            }
        }
    }
}


Form1.Designer.cs
Quellcode ausblenden C#-Code
namespace _266_Flaechenberechnung
{
    partial class Form1
    {
        /// <summary>
        /// Erforderliche Designervariable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Verwendete Ressourcen bereinigen.
        /// </summary>
        /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Vom Windows Form-Designer generierter Code

        /// <summary>
        /// Erforderliche Methode für die Designerunterstützung.
        /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(184, 11);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.Text = "266";
            this.ResumeLayout(false);

        }

        #endregion
    }
}
vote_ok
von Waldgeist (2310 Punkte) - 31.10.2019 um 18:51 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double hoehe = Convert.ToDouble(textBox1.Text);
            double breite = Convert.ToDouble(textBox2.Text);

            double Ergebnis = hoehe * breite;

            textBox3.Text = Ergebnis.ToString("#,#");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            double hoehe = Convert.ToDouble(textBox1.Text);
            double breite = Convert.ToDouble(textBox2.Text);

            double Ergebnis = 0.5 * hoehe * breite;

            textBox3.Text = Ergebnis.ToString("#,#");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Close();
        }

        
    }
}
vote_ok
von Janik (40 Punkte) - 31.10.2019 um 22:09 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Flächenberechnung
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cmdRechteck_Click(object sender, EventArgs e)
        {
            double Breite = Convert.ToDouble(txtEingabeBreite.Text);
            double Hoehe = Convert.ToDouble(txtEingabeHoehe.Text);

            double Flaeche = 0;

            Flaeche = Breite * Hoehe;

            txtAusgabe.Text = "Der Flächeninhalt ist " + Flaeche + " cm².";
        }

        private void cmdDreieck_Click(object sender, EventArgs e)
        {
            double Breite = Convert.ToDouble(txtEingabeBreite.Text);
            double Hoehe = Convert.ToDouble(txtEingabeHoehe.Text);

            double Flaeche = 0;

            Flaeche = 0.5*Breite * Hoehe;

            txtAusgabe.Text = "Der Flächeninhalt ist " + Flaeche + "cm²";

        }

        private void cmdEnde_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}


Ich bin noch ein kompletter Neuling, was das Programmieren angeht also verzeiht mir bitte, falls ich dumme Fehler gemacht habe ^^^
Ich danke euch auch jetzt schon mal vorab für eure Hilfe :)
vote_ok
von crazyfrien (80 Punkte) - 07.11.2019 um 11:04 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Flächenberechnung
{
    public partial class Form1 : Form
    {
        private double height = 0;
        private double width = 0;
        private double ergebnis = 0;
        private bool expanded = false;

        public Form f;
        public Label l1;
        public Label l2;
        public TextBox t1;
        public TextBox t2;
        public TextBox t3;
        public Button btn;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            f = new Form();

            l1 = new Label();
            l1.Text = "Höhe";
            l1.Top = 25;
            l1.Left = 25;

            l2 = new Label();
            l2.Text = "Breite";
            l2.Top = 50;
            l2.Left = 25;

            t1 = new TextBox();
            t1.Top = l1.Top;
            t1.Left = l1.Width+30;
            t1.Width = 150;

            t2 = new TextBox();
            t2.Top = l2.Top;
            t2.Left = l2.Width+30;
            t2.Width = 150;



            btn = new Button();
            btn.Text = "Bestätigen";
            btn.Left = 25;
            btn.Width = t2.Right;
            btn.Top = t2.Bottom + 10;
            btn.Click += Blubb;

            f.Width = t1.Right + 50;
            f.Height = btn.Bottom + 50;

            f.Controls.Add(l1);
            f.Controls.Add(l2);
            f.Controls.Add(t1);
            f.Controls.Add(t2);
            f.Controls.Add(btn);

            f.Show();
        }

        public void Blubb(object sender, EventArgs e)
        {
            height = Convert.ToInt32(t1.Text);
            width = Convert.ToInt32(t2.Text);
            f.Close();



            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!expanded)
            {
                double hvor = this.Height;
                double hsoll = this.Height + 30;
                for (int i = Convert.ToInt32(hvor); i < Convert.ToInt32(hsoll); i++)
                {
                    System.Threading.Thread.Sleep(5);
                    this.Height = i;
                }

                System.Threading.Thread.Sleep(500);
                expanded = true;
                showBlubb();
            }
            ergebnis = height * width;
            showErgebnis();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!expanded)
            {
                double hvor = this.Height;
                double hsoll = this.Height + 30;
                for (int i = Convert.ToInt32(hvor); i < Convert.ToInt32(hsoll); i++)
                {
                    System.Threading.Thread.Sleep(5);
                    this.Height = i;
                }

                System.Threading.Thread.Sleep(500);
                expanded = true;
                showBlubb();
            }
            ergebnis = (height * width) / 2;
            showErgebnis();
        }
        private void showBlubb()
        {
            t3 = new TextBox();
            t3.Width = this.Width - 50;
            t3.Left = 15;
            t3.Top = button2.Bottom + 10;
            t3.ReadOnly = true;
            this.Controls.Add(t3);
        }
        private void showErgebnis()
        {
            t3.Text = Convert.ToString(ergebnis);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.google.com/search?q=dieses+Programm+funktioniert&rlz=1C1GCEU_deDE819DE819&oq=Dieses+Programm+funktioniert&aqs=chrome.0.69i59j0.4258j0j7&sourceid=chrome&ie=UTF-8");
            Application.Exit();
        }
    }
}
1800882

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.