Теоретична частина
Парадигма — об'єктно-орієнтована. У Windows Forms ми часто зв'язуємо події елементів (натискання кнопки, зміна вибору) з обробниками — саме це й демонструємо.
Компоненти, що використовуються
- TextBox — введення рядка (речення).
- RadioButton — вибір одного з двох чисел (наприклад 1 або 2).
- CheckBox — можливість вибрати одну або дві дії.
- ComboBox — випадаючий список (у проекті — для вибору кольору тексту).
- Label — поле для виводу другого результату.
Логіка задачі. Зчитати речення → розбити на слова → зробити циклічний зсув на N позицій (N — вибране число).
Якщо обрано дві дії, вивести два варіанти (зсув на N та на N+1).
Рекомендації по розміщенню елементів у формі (Visual Studio)
- Створіть новий проект: Windows Forms App (.NET Framework або .NET)
- На Form1 помістіть:
TextBox textBoxInput,ComboBox comboColor, двіRadioButton radioN1, radioN2, дваCheckBox checkAction1, checkAction2, кнопкуbuttonProcess,TextBox textBoxResult(multiline=false) абоLabel labelResultтаLabel labelAltResult. - Задайте смислові імена елементам — це спрощує код і дебаг.
Word Shift Application
Word Shift Visualization
Код (Form1.cs)
Нижче — повний приклад коду для форми. Коментарі пояснюють кожен крок.
using System;
using System.Linq;
using System.Windows.Forms;
namespace WordShiftWinForms
{
partial class Form1
{
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
///
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.textBoxInput = new System.Windows.Forms.TextBox();
this.textBoxNumber = new System.Windows.Forms.TextBox();
this.comboColor = new System.Windows.Forms.ComboBox();
this.radioN1 = new System.Windows.Forms.RadioButton();
this.radioN2 = new System.Windows.Forms.RadioButton();
this.checkAction1 = new System.Windows.Forms.CheckBox();
this.checkAction2 = new System.Windows.Forms.CheckBox();
this.buttonProcess = new System.Windows.Forms.Button();
this.textBoxResult = new System.Windows.Forms.TextBox();
this.labelAltResult = new System.Windows.Forms.Label();
this.groupBoxOptions = new System.Windows.Forms.GroupBox();
this.groupBoxActions = new System.Windows.Forms.GroupBox();
this.labelInput = new System.Windows.Forms.Label();
this.labelNumber = new System.Windows.Forms.Label();
this.labelColor = new System.Windows.Forms.Label();
this.labelResult = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.groupBoxOptions.SuspendLayout();
this.groupBoxActions.SuspendLayout();
this.SuspendLayout();
//
// textBoxInput
//
this.textBoxInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxInput.Location = new System.Drawing.Point(15, 43);
this.textBoxInput.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.textBoxInput.Multiline = true;
this.textBoxInput.Name = "textBoxInput";
this.textBoxInput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxInput.Size = new System.Drawing.Size(590, 105);
this.textBoxInput.TabIndex = 0;
//
// textBoxNumber
//
this.textBoxNumber.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxNumber.Location = new System.Drawing.Point(15, 187);
this.textBoxNumber.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.textBoxNumber.Name = "textBoxNumber";
this.textBoxNumber.Size = new System.Drawing.Size(590, 26);
this.textBoxNumber.TabIndex = 1;
//
// comboColor
//
this.comboColor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboColor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboColor.FormattingEnabled = true;
this.comboColor.Location = new System.Drawing.Point(15, 249);
this.comboColor.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.comboColor.Name = "comboColor";
this.comboColor.Size = new System.Drawing.Size(590, 28);
this.comboColor.TabIndex = 2;
//
// radioN1
//
this.radioN1.AutoSize = true;
this.radioN1.Checked = true;
this.radioN1.Location = new System.Drawing.Point(8, 29);
this.radioN1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.radioN1.Name = "radioN1";
this.radioN1.Size = new System.Drawing.Size(54, 24);
this.radioN1.TabIndex = 0;
this.radioN1.TabStop = true;
this.radioN1.Text = "N1";
this.radioN1.UseVisualStyleBackColor = true;
//
// radioN2
//
this.radioN2.AutoSize = true;
this.radioN2.Location = new System.Drawing.Point(8, 63);
this.radioN2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.radioN2.Name = "radioN2";
this.radioN2.Size = new System.Drawing.Size(54, 24);
this.radioN2.TabIndex = 1;
this.radioN2.Text = "N2";
this.radioN2.UseVisualStyleBackColor = true;
//
// checkAction1
//
this.checkAction1.AutoSize = true;
this.checkAction1.Checked = true;
this.checkAction1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkAction1.Location = new System.Drawing.Point(8, 29);
this.checkAction1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.checkAction1.Name = "checkAction1";
this.checkAction1.Size = new System.Drawing.Size(93, 24);
this.checkAction1.TabIndex = 0;
this.checkAction1.Text = "Action 1";
this.checkAction1.UseVisualStyleBackColor = true;
//
// checkAction2
//
this.checkAction2.AutoSize = true;
this.checkAction2.Location = new System.Drawing.Point(8, 63);
this.checkAction2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.checkAction2.Name = "checkAction2";
this.checkAction2.Size = new System.Drawing.Size(93, 24);
this.checkAction2.TabIndex = 1;
this.checkAction2.Text = "Action 2";
this.checkAction2.UseVisualStyleBackColor = true;
//
// buttonProcess
//
this.buttonProcess.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.buttonProcess.Enabled = false;
this.buttonProcess.Location = new System.Drawing.Point(257, 427);
this.buttonProcess.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.buttonProcess.Name = "buttonProcess";
this.buttonProcess.Size = new System.Drawing.Size(109, 40);
this.buttonProcess.TabIndex = 7;
this.buttonProcess.Text = "Process";
this.buttonProcess.UseVisualStyleBackColor = true;
this.buttonProcess.Click += new System.EventHandler(this.buttonProcess_Click);
//
// textBoxResult
//
this.textBoxResult.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxResult.Location = new System.Drawing.Point(15, 493);
this.textBoxResult.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.textBoxResult.Multiline = true;
this.textBoxResult.Name = "textBoxResult";
this.textBoxResult.ReadOnly = true;
this.textBoxResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxResult.Size = new System.Drawing.Size(590, 105);
this.textBoxResult.TabIndex = 8;
//
// labelAltResult
//
this.labelAltResult.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelAltResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAltResult.Location = new System.Drawing.Point(15, 620);
this.labelAltResult.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelAltResult.Name = "labelAltResult";
this.labelAltResult.Size = new System.Drawing.Size(591, 53);
this.labelAltResult.TabIndex = 9;
this.labelAltResult.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// groupBoxOptions
//
this.groupBoxOptions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxOptions.Controls.Add(this.radioN1);
this.groupBoxOptions.Controls.Add(this.radioN2);
this.groupBoxOptions.Location = new System.Drawing.Point(15, 300);
this.groupBoxOptions.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBoxOptions.Name = "groupBoxOptions";
this.groupBoxOptions.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBoxOptions.Size = new System.Drawing.Size(257, 107);
this.groupBoxOptions.TabIndex = 3;
this.groupBoxOptions.TabStop = false;
this.groupBoxOptions.Text = "Options";
//
// groupBoxActions
//
this.groupBoxActions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxActions.Controls.Add(this.checkAction1);
this.groupBoxActions.Controls.Add(this.checkAction2);
this.groupBoxActions.Location = new System.Drawing.Point(350, 300);
this.groupBoxActions.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBoxActions.Name = "groupBoxActions";
this.groupBoxActions.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBoxActions.Size = new System.Drawing.Size(257, 107);
this.groupBoxActions.TabIndex = 4;
this.groupBoxActions.TabStop = false;
this.groupBoxActions.Text = "Actions";
//
// labelInput
//
this.labelInput.AutoSize = true;
this.labelInput.Location = new System.Drawing.Point(15, 19);
this.labelInput.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelInput.Name = "labelInput";
this.labelInput.Size = new System.Drawing.Size(84, 20);
this.labelInput.TabIndex = 10;
this.labelInput.Text = "Input Text:";
//
// labelNumber
//
this.labelNumber.AutoSize = true;
this.labelNumber.Location = new System.Drawing.Point(15, 163);
this.labelNumber.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelNumber.Name = "labelNumber";
this.labelNumber.Size = new System.Drawing.Size(110, 20);
this.labelNumber.TabIndex = 11;
this.labelNumber.Text = "Number Input:";
//
// labelColor
//
this.labelColor.AutoSize = true;
this.labelColor.Location = new System.Drawing.Point(15, 225);
this.labelColor.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(50, 20);
this.labelColor.TabIndex = 12;
this.labelColor.Text = "Color:";
//
// labelResult
//
this.labelResult.AutoSize = true;
this.labelResult.Location = new System.Drawing.Point(15, 469);
this.labelResult.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelResult.Name = "labelResult";
this.labelResult.Size = new System.Drawing.Size(59, 20);
this.labelResult.TabIndex = 13;
this.labelResult.Text = "Result:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(437, 433);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(81, 37);
this.button1.TabIndex = 14;
this.button1.Text = "Exit";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(622, 695);
this.Controls.Add(this.button1);
this.Controls.Add(this.labelResult);
this.Controls.Add(this.labelColor);
this.Controls.Add(this.labelNumber);
this.Controls.Add(this.labelInput);
this.Controls.Add(this.groupBoxActions);
this.Controls.Add(this.groupBoxOptions);
this.Controls.Add(this.labelAltResult);
this.Controls.Add(this.textBoxResult);
this.Controls.Add(this.buttonProcess);
this.Controls.Add(this.comboColor);
this.Controls.Add(this.textBoxNumber);
this.Controls.Add(this.textBoxInput);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.MinimumSize = new System.Drawing.Size(637, 728);
this.Name = "Form1";
this.Text = "Word Shift Application";
this.groupBoxOptions.ResumeLayout(false);
this.groupBoxOptions.PerformLayout();
this.groupBoxActions.ResumeLayout(false);
this.groupBoxActions.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxInput;
private TextBox textBoxNumber;
private ComboBox comboColor;
private RadioButton radioN1;
private RadioButton radioN2;
private CheckBox checkAction1;
private CheckBox checkAction2;
private Button buttonProcess;
private TextBox textBoxResult;
private Label labelAltResult;
private GroupBox groupBoxOptions;
private GroupBox groupBoxActions;
private Label labelInput;
private Label labelNumber;
private Label labelColor;
private Label labelResult;
private Button button1;
}
}
Код (Form1.cs)
using System;
using System.Linq;
using System.Windows.Forms;
namespace WordShiftWinForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Ініціалізація ComboBox кольорів
comboColor.Items.AddRange(new object[] { "Black", "Blue", "Green", "Purple", "Red" });
comboColor.SelectedItem = "Purple"; // значення за замовчуванням
comboColor.SelectedIndexChanged += ComboColor_SelectedIndexChanged;
// Заборона вводу нецифр у числове поле (TextBoxNumber)
textBoxNumber.KeyPress += TextBoxNumber_KeyPress;
// Відстежуємо зміни для активації кнопки
textBoxInput.TextChanged += UpdateButtonState;
textBoxNumber.TextChanged += UpdateButtonState;
comboColor.SelectedIndexChanged += UpdateButtonState;
radioN1.CheckedChanged += UpdateButtonState;
radioN2.CheckedChanged += UpdateButtonState;
checkAction1.CheckedChanged += UpdateButtonState;
checkAction2.CheckedChanged += UpdateButtonState;
// Початковий стан кнопки
buttonProcess.Enabled = false;
}
// Обробник зміни кольору (ComboBox)
private void ComboColor_SelectedIndexChanged(object sender, EventArgs e)
{
string colorName = comboColor.SelectedItem?.ToString() ?? "Black";
textBoxInput.ForeColor = System.Drawing.Color.FromName(colorName);
}
// Заборона вводу символів, крім цифр та пробілу
private void TextBoxNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != ' ')
{
e.Handled = true; // блокувати всі інші символи
}
}
// Перевірка, чи можна активувати кнопку
private void UpdateButtonState(object sender, EventArgs e)
{
bool inputFilled = !string.IsNullOrWhiteSpace(textBoxInput.Text);
bool numberFilled = !string.IsNullOrWhiteSpace(textBoxNumber.Text);
bool colorSelected = comboColor.SelectedIndex >= 0;
bool radioSelected = radioN1.Checked || radioN2.Checked;
bool checkboxSelected = checkAction1.Checked || checkAction2.Checked;
buttonProcess.Enabled = inputFilled && numberFilled && colorSelected && radioSelected && checkboxSelected;
}
// Кнопка обробки
private void buttonProcess_Click(object sender, EventArgs e)
{
string input = textBoxInput.Text.Trim();
string[] words = input.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
int shift = radioN1.Checked ? 1 : 2;
textBoxResult.Text = string.Empty;
labelAltResult.Text = string.Empty;
if (checkAction1.Checked)
{
textBoxResult.Text = ShiftLeft(words, shift);
}
if (checkAction2.Checked)
{
labelAltResult.Text = ShiftLeft(words, shift + 1);
}
}
// Зсув вліво на shift позицій
private string ShiftLeft(string[] words, int shift)
{
int n = words.Length;
if (n == 0) return string.Empty;
shift = ((shift % n) + n) % n;
string[] res = new string[n];
for (int i = 0; i < n; i++)
{
res[i] = words[(i + shift) % n];
}
return string.Join(" ", res);
}
}
}
Пояснення вибору зсувів: В коді використано зсув вліво (ShiftLeft) — це відповідає прикладу: з 1 2 3 4 5 при shift=2 отримаємо 3 4 5 1 2. Якщо бажаєте зсув праворуч — змініть індекс обчислення.
Ініціалізація компонентів (коротка)
У InitializeComponent() додайте елементи і прив'яжіть обробник до кнопки:
// Приклад (фрагмент)
// buttonProcess.Click += new EventHandler(this.buttonProcess_Click);
// radioN1.Checked = true;
// comboColor.SelectedIndex = 3; // Purple
Порада: Завжди перевіряйте розбиття рядка: користувач може ввести багато пробілів. Використовуємо
StringSplitOptions.RemoveEmptyEntries.
🐸