Суть в том, что есть кусочек кода, который выводит результат работы в консоль, а необходимо, чтобы он выводил на экран формы windows forms, несколько часов гугления не помогли
int a = 1;
int b = a;
int c;
for (int i = 0; i < 8; i++) {
c = a + b;
a = b;
b = c;
Console.WriteLine(c);
System.Threading.Thread.Sleep(1000);
}
-
Вопрос задан
-
14017 просмотров
Пригласить эксперта
int a = 1;
int b = a;
int c;
//Создаем форму
System.Windows.Forms.Form form = new System.Windows.Forms.Form();
//Задаем размер
form.Size = new System.Drawing.Size(640, 480);
//Создаем текстовое поле
System.Windows.Forms.RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();
//Задаем размер поля на всю форму
richTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
//Добавляем поле на форму
form.Controls.Add(richTextBox);
for (int i = 0; i < 8; i++) {
c = a + b;
a = b;
b = c;
//Записываем значение текста с новой строки
richTextBox.Text = richTextBox.Text + c + System.Environment.NewLine;
System.Threading.Thread.Sleep(1000);
}
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
Как перейти от Waterfall к Agile
EggHead 06.05.2025
Каскадная модель разработки Waterfall — классический пример того, как благие намерения превращаются в организационный кошмар. Изначально созданная для упорядочивания хаоса и внесения предсказуемости. . .
Оптимизация SQL запросов — Продвинутые техники
Codd 06.05.2025
Интересно наблюдать эволюцию подходов к оптимизации. Двадцать лет назад всё сводилось к нескольким простым правилам: «Избегайте SELECT *», «Используйте индексы», «Не джойните слишком много таблиц». . . .
Создание микросервисов с gRPC и Protobuf в C++
bytestream 06.05.2025
Монолитные приложения, которые ещё недавно считались стандартом индустрии, уступают место микросервисной архитектуре — подходу, при котором система разбивается на небольшие автономные сервисы, каждый. . .
Многопоточность и параллелизм в Python: потоки, процессы и гринлеты
py-thonny 06.05.2025
Параллелизм и конкурентность — две стороны многопоточной медали, которые постоянно путают даже бывалые разработчики.
Конкурентность (concurrency) — это когда ваша программа умеет жонглировать. . .
Распределенное обучение с TensorFlow и Python
AI_Generated 05.05.2025
В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .
CRUD API на C# и GraphQL
stackOverflow 05.05.2025
В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Although it is possible to use a simple MessageBox for printing messages, it is sometimes convenient to use a window that you have more control over. Below, I have the C# code for a simple console application named “MyConsoleApplication.” I created the project using the Console Application template, which creates the empty Main() function shown below. The code file is named “Program.cs” for simplicity, but it could be named anything.
We need to add a reference to the assembly System.Windows.Forms, in order to be able create Forms in the code. We also need to add the corresponding using directive using System.Windows.Forms; at the top of the code file. Finally, we need to add a reference to the assembly System.Drawing in order to set the size of the Form in the line: qMyForm.ClientSize = qMyTextbox.Size;.
Beyond that, the code that I have added is all inside the Main() function. First, I create a Form and add the text “An Important Message” to the title bar. Next, I create a TextBox and set its size to 400 by 300 pixels. Then I set it to accept multiple lines of text, enable the vertical scrollbar to accommodate text overruns, and set it to be read only so that the text cannot be modified.
The middle block of code consists of several calls to the member function AppendText(). Each call adds a line of text from the Bible, Proverbs 4:10-13. The character sequence \u000D\u000A is the unicode representation of the carriage return and linefeed characters. So, that moves the text to the beginning of the next line. On a related note, the TextBox has word wrap enabled by default.
The third block of code sets the size of the containing Form to have a client area that is the same size as the TextBox. Then the TextBox is added to the Form, and the Form is displayed via a call to ShowDialog().
The output of the program looks like this:
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FormStringOutput; using System.Windows.Forms; namespace MyConsoleApplication { class Program { static void Main(string[] args) { Form qMyForm = new Form(); // Sets the title bar text qMyForm.Text = "An Important Message"; TextBox qMyTextbox = new TextBox(); qMyTextbox.SetBounds(0, 0, 400, 300); qMyTextbox.Multiline = true; qMyTextbox.ScrollBars = ScrollBars.Vertical; qMyTextbox.ReadOnly = true; // Add messages via AppendText, using '\u000D\u000A' for new line characters qMyTextbox.AppendText("Hear, my child, and accept my words,\u000D\u000A"); qMyTextbox.AppendText(" that the years of your life may be many.\u000D\u000A"); qMyTextbox.AppendText("I have taught you the way of wisdom;\u000D\u000A"); qMyTextbox.AppendText(" I have led you in the paths of uprightness.\u000D\u000A"); qMyTextbox.AppendText("When you walk, your step will not be hampered;\u000D\u000A"); qMyTextbox.AppendText(" and if you run, you will not stumble.\u000D\u000A"); qMyTextbox.AppendText("Keep hold of instruction; do not let go;\u000D\u000A"); qMyTextbox.AppendText(" guard her, for she is your life.\u000D\u000A"); qMyTextbox.AppendText("\u000D\u000A Proverbs 4:10-13\u000D\u000A"); // Set the client area of the form equal to the size of the Text Box qMyForm.ClientSize = qMyTextbox.Size; // Add the Textbox to the form qMyForm.Controls.Add(qMyTextbox); // Display the form qMyForm.ShowDialog(); } } }
Tags: C Sharp, C#, form, GUI, message, message box, microsoft, programming, simple, text, textbox, windows
Michael Hall
By: Michael Hall
This entry was posted on Wednesday, August 6th, 2014 at 11:49 am and is filed under C Sharp. You can follow any responses to this entry through the RSS 2.0 feed.Both comments and pings are currently closed.
Отображение текста в форме Windows Forms
Отобразить
текст можно в самых различных элементах
управления, однако основным элементом
в программе, в котором выводится текст,
является Label. При добавлении надписи в
форму цвет фона совпадет с цветом формы
так, что виден только текст. Можно
изменить свойство BackColor надписи.
Для
отображения текста в надписи свойству
Text следует задать определенное значение.
Свойство Font определяет шрифт для
отображения текста, содержащегося в
свойстве Text. Свойство ForeColor определяет
непосредственно цвет текста.
Отображение текста в надписи
-
В
меню Файл
выберите команду Создать
проект. -
В
диалоговом окне Создание
проекта
выберите Приложение
Windows Forms,
а затем нажмите кнопку ОК.
Откроется
новый проект Windows Forms.
-
Из
панели
элементов
перетащите в форму элемент управления
Label. -
Добавьте
элемент управления Button
в форму и измените следующие свойства.Свойство
Значение
Имя
changeText
Текст
Изменить
текстРазмер
80,
23 -
Дважды
щелкните кнопку, чтобы создать обработчик
событий changeText_Click,
и добавьте следующий код.this.label1.Text
= «Time
»
+ DateTime.Now.ToLongTimeString(); -
Add
another Button
control to the form, and change the following propertiesProperty
Value
Name
changeColor
Text
Change
ColorSize
80,
23 -
Double-click
the button to create the changeColor_Click
event handler, and add the following code:Random
randomColor = new
Random();this.label1.ForeColor
= Color.FromArgb(randomColor.Next(0, 256),randomColor.Next(0,
256), randomColor.Next(0, 256)); -
Press
F5 to run the program. -
Click
Change
Text
and verify that the text in the label is updated. -
Click
Change
Color
and verify that the font of the text is changed to a new color.
How
to: Use TextBox Controls to Get User Input
You
can both display text and retrieve text from users by using a TextBox
control. After a user types data in a TextBox, you can retrieve this
data by using the Text property. By default, the Multiline property
of the TextBox is set to false.
This means that users cannot press the ENTER key to create multiple
lines of text in the TextBox. You can set the Multiline property to
true
to enable this.
-
Добавьте
в форму другой элемент управления
Button
и измените следующие свойства.Свойство
Значение
Имя
changeColor
Текст
Изменить
цветРазмер
80,
23 -
Дважды
щелкните кнопку, чтобы создать обработчик
событий changeColor_Click,
и добавьте следующий код.Random
randomColor = new
Random();this.label1.ForeColor
= Color.FromArgb(randomColor.Next(0, 256),randomColor.Next(0,
256), randomColor.Next(0, 256)); -
Нажмите
клавишу F5 для выполнения программы. -
Нажмите
кнопку Изменить
текст
и убедитесь, что текст в надписи обновлен. -
Нажмите
кнопку Изменить
цвет
и убедитесь, изменился цвет шрифта
текста.
Использование элемента управления
«TextBox» для получения вводимых данных
С
помощью элемента управления TextBox
можно как отображать текст, так и получать
его от пользователя. Введенные
пользователем данные в TextBox
можно получить с помощью свойства Text.
По умолчанию свойство Multiline
TextBox
имеет значение false.
Это означает, что пользователь не может
нажимать клавишу ВВОД для создания
нескольких строк текста в TextBox.
Для включения этой возможности установите
для свойства Multiline значение true.
To retrieve input typed in
a text box
-
On
the File
menu, click NewProject. -
In
the New
Project
dialog box, click Windows
Forms Application,
and then click OK.
A
new Windows Forms project opens.
-
From
the Toolbox,
drag a TextBox
control onto the form, and change the following properties in the
Properties
window:Property
Value
Name
inputText
Multiline
True
Size
175,
90 -
Add
a Button
control next to the text box, and change the following properties:Property
Value
Name
retrieveInput
Text
Retrieve
-
Double-click
the button to create the retrieveInput_Click
event handler, and add the following code:MessageBox.Show(this.inputText.Text);
-
Press
F5 to run the program. -
Type
multiple lines of text in the text box, and then click Retrieve. -
Verify
that the message displays all the text that you typed in the text
box.
Извлечение введенных в текстовое поле
данных
-
В
меню Файл
выберите команду Создать
проект. -
В
диалоговом окне Создание
проекта
выберите Приложение
Windows Forms,
а затем нажмите кнопку ОК.
Откроется
новый проект Windows Forms.
-
Перетащите
элемент управления TextBox
из панели
элементов
в форму и измените следующие свойства
в окне Свойства.Свойство
Значение
Имя
inputText
Многострочность
True
Размер
175,
90 -
Добавьте
элемент управления Кнопка
в форму и измените следующие свойства.Свойство
Значение
Имя
retrieveInput
Текст
Извлечь
-
Дважды
щелкните кнопку для создания обработчика
событий retrieveInput_Click
и добавьте следующий код.MessageBox.Show(this.inputText.Text);
-
Нажмите
клавишу F5 для выполнения программы. -
Введите
несколько строк текста в текстовом
поле и нажмите кнопку Извлечь. -
Убедитесь,
что сообщение отображает весь текст,
введенный в текстовое поле.
How to: Convert the Text in a TextBox Control to an Integer
When
you provide a TextBox control in your application to retrieve a
numeric value, you often have to convert the text (a string) to a
numeric value, such as an integer. This example demonstrates
two methods of converting text data to integer data.
Example
int
anInteger anInteger |
Compiling
the Code
This
example requires:
-
A
TextBox control named textBox1.
Robust
Programming
The
following conditions may cause an exception:
-
The
text converts to a number that is too large or too small to store as
an int. -
The
text may not represent a number.
Преобразование текста в элементе
управления «TextBox» в целое число
Если
в приложении используется элемент
управления TextBox для извлечения числовых
значений, часто приходится преобразовывать
текст (строку) в числовое значение,
например целое число. В этом примере
показано два способа преобразования
текстовых данных в целочисленные.
Пример
int
anInteger anInteger |
Компиляция кода3
Для
этого примера необходимы следующие
компоненты.
-
Элемент
управления TextBox с именем textBox1.
Надежное программирование
Исключение
может возникнуть при следующих условиях.
-
Текст
преобразуется в число, которое слишком
велико или мало для сохранения в качестве
int. -
Возможно,
текст не представляет число.
How to: Set the Selected
Text in a TextBox Control
This
example programmatically selects text in a Windows Forms TextBox
control and retrieves the selected text.
Example
private {
textBox1.Text
textBox1.Select(6, MessageBox.Show(textBox1.SelectedText); } |
Compiling the Code
This
example requires:
-
A
form with a TextBox control named textBox1
and a Button control named button1.
Set the Click
event handler of button1
to button1_Click.
Note: |
The |
Robust Programming
In
this example you are setting the Text property before you retrieve
the SelectedText
value. In most cases, you will be retrieving text typed by the user.
Therefore, you will want to add error-handling code in case the text
is too short.
Установка выделения текста в элементе
управления «TextBox»
В
этом примере в элементе управления
Windows Forms TextBox текст выделяется программным
путем, а затем извлекается.
Пример
private {
textBox1.Text
textBox1.Select(6, MessageBox.Show(textBox1.SelectedText); } |
Компиляция кода4
Для
этого примера необходимы следующие
компоненты.
-
Форма
с элементом управления TextBox с именем
textBox1
и с элементом управления Button с именем
button1.
Задайте обработчику событий Click
для button1
значение button1_Click.
Примечание. |
Код |
Надежное программирование
В
этом примере перед извлечением значения
SelectedText
устанавливается свойство Text. В большинстве
случаев извлекается текст, введенный
пользователем. Поэтому если текст
слишком короток, в код рекомендуется
добавить обработчик ошибок.
How to: Format Characters in a RichTextBox Control
This
example writes a sentence, which contains three words in three
different font styles (bold, italic, and underlined), to an existing
RichTextBox control.
Example
richTextBox1.Rtf
@»this
@»and |
Compiling the
Code
This
example requires: A RichTextBox control named richTextBox1.
Robust
Programming
The
rich text format is very flexible, but any errors in the format lead
to errors in the displayed text.
Форматирование знаков в элементе
управления «RichTextBox»
В
этом примере выполняется запись
предложения, содержащего три слова,
написанных разными шрифтами (полужирным,
курсивом и с подчеркиванием), в существующий
элемент управления RichTextBox.
Пример
richTextBox1.Rtf @»and |
Компиляция кода5
Для
этого примера необходимы следующие
компоненты. Элемент управления RichTextBox
с именем richTextBox.
Надежное программирование
Расширенный
текстовый формат очень гибок, но любая
ошибка в формате приведет к ошибкам в
отображаемом тексте.
How to: Load Text into a RichTextBox Control
This
example loads a text file that a user selects in the OpenFileDialog.
The
code then populates a RichTextBox control with the file’s contents.
Example
//
Create an OpenFileDialog object.
OpenFileDialog
openFile1 = new
OpenFileDialog();
//
Initialize the filter to look for text files.
openFile1.Filter
= «Text
Files|*.txt»;
//
If the user selected a file, load its contents into the RichTextBox.
if
(openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
richTextBox1.LoadFile(openFile1.FileName,
RichTextBoxStreamType.PlainText);
Compiling
the Code
This
example requires:
-
A
RichTextBox control named richTextBox1.
Insert the code segment into the Form1_Load
method. When you run the program, you will be prompted to select a
text file.
Загрузка текста в элемент управления
«RichTextBox»
В
этом примере выполняется загрузка
текстового файла, выбранного пользователем
в OpenFileDialog. Затем код заполняет элемент
управления RichTextBox содержимым файла.
Пример
//
Create
an
OpenFileDialog
object.
OpenFileDialog
openFile1 = new
OpenFileDialog();
//
Initialize the filter to look for
text files.
openFile1.Filter
= «Text
Files|*.txt»;
//
If the user selected a file, load its contents into the RichTextBox.
if
(openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
richTextBox1.LoadFile(openFile1.FileName,
RichTextBoxStreamType.PlainText);
Компиляция кода
Для
этого примера необходимы следующие
компоненты.
-
Элемент
управления RichTextBox с именем richTextBox1.
Вставьте сегмент кода в метод Form1_Load.6
При выполнении программы будет выведен
запрос на выбор текстового файла.
Dialog Boxes
How to: Retrieve Data
from a Dialog Box
Dialog boxes enable
your program to interact with users and retrieve data that users have
entered in the dialog box for use in your application. There are
several built-in dialog boxes that you can use in your applications.
You can also create your own dialog boxes.
A
common task in Windows Forms development is displaying a dialog box
to collect information when a user clicks a button on the main form
of an application. You can see an example of this in the Visual C#
Express Edition IDE. When you add a ListBox control to a form, you
can click the Items
property in the Properties
window to display a dialog box. This dialog box enables you to
quickly type text on separate lines of a text box. The
application then adds each line of text to ListBox control when you
click OK.
If you want to let users add their own items to a list box in your
application, you can create your own string editor dialog box.
Диалоговые окна
Извлечение данных из диалогового окна
Диалоговые
окна позволяют программе взаимодействовать
с пользователями и извлекать данные,
введенные ими в диалоговое окно, в
приложение. Существует несколько
встроенных, доступных для использования
в приложениях, диалоговых окон. Можно
также создавать свои собственные
диалоговые окна.
Стандартной
задачей при разработке Windows
Forms является отображение
диалогового окна для сбора информации
после нажатия пользователем кнопки в
основной форме приложения. В следующем
примере показано, как сделать это в
Visual C#,
экспресс-выпуск IDE. После
добавления элемента управления ListBox
в форму выберите свойство Элементы
в окне Свойства для открытия
диалогового окна. C помощью
этого диалогового окна можно быстро
ввести текст на нескольких строках
текстового поля. После нажатия кнопки
ОК приложение добавит каждую строку
текста к элементу управления ListBox.
Для того чтобы пользователи могли
добавлять к списку произвольные элементы,
необходимо создать свое собственное
диалоговое окно редактора строк.
To create the
main form of your application
-
On
the File
menu, click New
Project.
The
New
Project
dialog box appears.
-
Click
Windows
Forms Application,
and then click OK.
A
form named Form1 is added to the project.
-
From
the Toolbox,
drag a ListBox
control to the form, and change the following property in the
Properties
window:Property
Value
Modifiers
Public
-
Add
a Button
control to the form, and change the following properties in the
Properties
window:
-
Property
Value
Name
addItems
Text
Add
To create a dialog box
-
On
the Project
menu, click Add
Windows Form,
leave the default name Form2,
and then click Add. -
From
the Toolbox,
drag a Label control to the form, and change the Text
property to Enter
the String (one per line). -
Add
a TextBox control to the form, and change the following properties
in the Properties
window.
-
Property
Value
Multiline
True
Scrollbars
Both
Size
255,
160
Создание основной
формы приложения
-
В
меню Файл
выберите команду Создать
проект.
Откроется
диалоговое окно Создание
проекта.
-
Выберите
элемент Приложение
Windows Forms
и нажмите кнопку ОК.
Форма
с именем Form1 добавится к проекту.
-
Перетащите
элемент управления ListBox
из панели
элементов
в форму и измените следующие свойства
в окне Свойства.Свойство
Значение
Модификаторы
Public
-
Добавьте
элемент управления Button
в форму и измените следующие свойства
в окне Свойства.
-
Свойство
Значение
Имя
addItems
Текст
Добавить
Создание диалогового окна
-
В
меню Проект
выберите Добавить
форму Windows,
оставьте имя по умолчанию Form2,
затем щелкните Добавить. -
Перетащите
элемент управления Label из панели
элементов
в форму и измените свойства Текст
на Введите
элементы (по одному на каждой строке). -
Добавьте
элемент управления TextBox в форму и
измените следующие свойства в окне
Свойства.Свойство
Значение
Многострочность
True
Полосы
прокруткиОбе
Размер
255,
160 -
Add
a Button control to the form, and change the following properties in
the Properties
window:
-
Property
Value
Name
okButton
Text
OK
Retrieving Data from a
Dialog Box
There
are several ways you can pass data from one Windows form to another.
In this example, you will pass Form1
to the constructor of Form2.
Last Updated :
17 Apr, 2023
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the following steps:
2. Run-Time: It is a little bit tricky than the above method. In this method, you can set the Text property of the TextBox programmatically with the help of given syntax:
public override string Text { get; set; }
Here, the text is represented in the form of String. Following steps are used to set the Text property of the TextBox:
- Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox TextBox Mytextbox = new TextBox();
- Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.
// Set Text property Mytextbox.Text = "Enter City Name...";
- Step 3 : And last add this textbox control to form using Add() method.
// Add this textbox to form this.Controls.Add(Mytextbox);
- Example:
CSharp
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
my {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label Mylablel =
new
Label();
Mylablel.Location =
new
Point(96, 54);
Mylablel.Text = "City";
Mylablel.AutoSize =
true
;
Mylablel.BackColor = Color.LightGray;
this
.Controls.Add(Mylablel);
TextBox Mytextbox =
new
TextBox();
Mytextbox.Location =
new
Point(187, 51);
Mytextbox.BackColor = Color.LightGray;
Mytextbox.ForeColor = Color.DarkOliveGreen;
Mytextbox.AutoSize =
true
;
Mytextbox.Name = "text_box1";
Mytextbox.Text = "Enter City Name...";
this
.Controls.Add(Mytextbox);
}
}
}
- Output: