C# :: Aufgabe #266 :: Lösung #2

4 Lösungen Lösungen öffentlich
#266

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ß :)
#2
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
    }
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben
1815122

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.