подключения
1 2 3 4 |
using System.IO;//работа с файлами using System.Text.RegularExpressions;//подключаем регулярные выражения using System.Collections;//содержит ArrayList using System.Runtime.InteropServices;//для подключения длл |
Вывод сообщения MessageBox.Show
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
private void button_Click(object sender, RoutedEventArgs e) { string caption = "caption"; string text = "This is text"; MessageBoxButton button= MessageBoxButton.YesNoCancel;//добавляем кнопку MessageBoxImage icon = MessageBoxImage.Warning;//предупреждение MessageBoxResult res= MessageBox.Show(text, caption, button, icon); if(res==MessageBoxResult.Yes) { MessageBox.Show("Yes"); } else if(res==MessageBoxResult.No) { MessageBox.Show("No"); } else if(res==MessageBoxResult.Cancel) { MessageBox.Show("Cancel"); } |
перевод из int в string
1 2 3 4 |
int n = 100; string s = Convert.ToString(n, 10); MessageBox.Show("n= "+s); return; |
Создание потока
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void button_Click(object sender, RoutedEventArgs e) { System.Threading.Thread t = new System.Threading.Thread(f); t.IsBackground = true;//делаем чтобы поток был не фоновым t.Start(); MessageBox.Show("end-button"); } private void f() { //задержка MessageBox.Show("f-start"); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); MessageBox.Show("f-end"); } |
Использование таймеров
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public int count; System.Windows.Threading.DispatcherTimer timer; public MainWindow() { InitializeComponent(); count = 0; textBox.Text = "One one one!"; } private void button_Click(object sender, RoutedEventArgs e) { //создаем таймер timer = new System.Windows.Threading.DispatcherTimer(); timer.Tick += new EventHandler(f_timer); timer.Interval = new TimeSpan(0, 0, 1);//1 секунд timer.Start();//запускаем таймер } private void f_timer(object sender, EventArgs e) { string s = Convert.ToString(count, 10); textBox.Text = s; count++; if (count == 5) timer.Stop();//останавливаем таймер } |
Перегрузить крестик чтобы при закрытии вызвалась функция
Нам нужно при закрытии программы через крестик вызвать функцию свою собственную. Почитать за нее можно тут. Мы работаем с классом System.Windows, с его методами. Добавим событие Closing. В классе определяем функцию обработчик, вот ее код
1 2 3 4 |
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { MessageBox.Show("Closing called"); } |
Теперь нам нужно сделать так называемую «подписку на события» — это общие объекты конфигурации, про нее почитать можно тут.
Назначить подписку на события мы можем в конструкторе в коде прописав следующий код в нем
1 2 3 4 5 6 7 8 9 |
public MainWindow() { InitializeComponent(); m_count = 0; textBox.Text = "One one one!"; //подписка на событие Closing Closing += MainWindow_Closing; } |
или в самом XAML коде строчка Closing=»MainWindow_Closing»
1 2 3 4 5 6 7 8 9 10 |
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="328.873" Width="587.248" Closing="MainWindow_Closing" > |
Общие диалоговые окна (открытие файла, сохранения и печати)
Почитать за это можно тут.
Октрытие файла
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private void button1_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "documetn";//по умолчанию имя файла dlg.DefaultExt = ".txt";//расширение файла по умолчанию dlg.Filter = "Text documents (.txt)|*.txt";//фильтра разширения //показать диалог открытия файла Nullable<bool> result = dlg.ShowDialog(); if(result== true) { //Открываем документ string filename = dlg.FileName; MessageBox.Show(filename); } } |
Сохранение файлов
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void button1_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document";//по умолчанию имя файла dlg.DefaultExt = ".txt";//по умолчанию расширение файла dlg.Filter = "Text document (.txt)|*.txt";//фильтер расширения файла //показать диалог Nullable<bool> result = dlg.ShowDialog(); if(result== true) { string filename = dlg.FileName; MessageBox.Show(filename); } } |
Диалоговое окно печати
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private void button1_Click(object sender, RoutedEventArgs e) { // конфигурировать диалог печати System.Windows.Controls.PrintDialog dlg = new System.Windows.Controls.PrintDialog(); dlg.PageRangeSelection = PageRangeSelection.AllPages; dlg.UserPageRangeEnabled = true; // показать диалог печати Nullable<bool> result = dlg.ShowDialog(); // процесс сохранения результатов диалогового окна if (result == true) { // печатать документ } } |
Создание модального диалогового окна
Создаем окно WPF вот его код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Window x:Class="WpfApplication1.Dialog2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="Dialog2" Height="300" Width="300"> <Grid> <Button x:Name="button" Content="Ok" HorizontalAlignment="Left" Margin="99,223,0,0" VerticalAlignment="Top" Width="75" IsDefault="True" Click="button_Click"/> <Button x:Name="button1" Content="Cancel" HorizontalAlignment="Left" Margin="194,223,0,0" VerticalAlignment="Top" Width="75" IsCancel="True"/> <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="30" Margin="79,90,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="181"/> </Grid> </Window> |
Обработчик кнопки Ок
1 2 3 4 5 |
private void button_Click(object sender, RoutedEventArgs e) { DialogResult = true;//устанавливаем возврат из ShowDialog Close();//закрываем окно } |
И обработчик кнопки по которому вызывается диалог
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
private void button1_Click(object sender, RoutedEventArgs e) { DialogW dlg = new DialogW(); //конфигурация диалог бокса dlg.Owner = this;//устанавливает связь с главным окном dlg.edit.Text = "hellow world!"; //открываем диалог Nullable<bool> result=dlg.ShowDialog(); if(result== true) { string s = dlg.edit.Text; MessageBox.Show("Ok s="+s); } else { MessageBox.Show("Cancel"); } } |
Создание таймера
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication2 { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { public int m_count;//счетчик System.Windows.Threading.DispatcherTimer m_timer; public MainWindow() { InitializeComponent(); m_count = 0; } private void button_Click(object sender, RoutedEventArgs e) { //Подписка на событие m_timer = new System.Windows.Threading.DispatcherTimer();//инициализация таймера m_timer.Tick += new EventHandler(f_timer);//подписка на событие m_timer.Interval=new TimeSpan(0, 0, 1);//1 секунда m_timer.Start();//запускаем таймер } //функция таймер private void f_timer(object sender, EventArgs e) { textBox.Text = Convert.ToString(m_count++, 10); if (m_count == 10) m_timer.Stop();//останавливаем таймер } } } |
Создание потока
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication3 { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { public int m_count;// переменная через которую мы обновляем поле System.Windows.Threading.DispatcherTimer m_timer; //создаем объект для блокировки private Object m_thisLock = new Object(); public MainWindow() { InitializeComponent(); m_count = 0; } private void button_Click(object sender, RoutedEventArgs e) { //Создаем таймер через который будем обновлят TextBox m_timer = new System.Windows.Threading.DispatcherTimer(); m_timer.Tick += new EventHandler(f_timer);//подписка на событие таймера m_timer.Interval = new TimeSpan(0, 0, 1);//интервал вызова таймера m_timer.Start(); System.Threading.Thread t = new System.Threading.Thread(f_thread); t.IsBackground = true; //запрещаем поток в фоновом режиме t.Start(); } private void f_timer(object sender, EventArgs e) { //обновляем TextBox textBox.Text = Convert.ToString(m_count, 10); } //функция потока private void f_thread() { //блокируем m_count lock (m_thisLock) { for (int i = 0; i < 1000; i++) { //делаем задержку System.Threading.Thread.Sleep(TimeSpan.FromSeconds(0.1)); m_count = i; } } m_timer.Stop();//останавливаем таймер MessageBox.Show("end timer"); } } } |
Еще один пример с остановкой потока
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication3 { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { public int m_count;// переменная через которую мы обновляем поле System.Windows.Threading.DispatcherTimer m_timer; bool m_flag; //создаем объект для блокировки private Object m_thisLock = new Object(); public MainWindow() { InitializeComponent(); m_flag = true; m_count = 0; } private void button_Click(object sender, RoutedEventArgs e) { //Создаем таймер через который будем обновлят TextBox m_timer = new System.Windows.Threading.DispatcherTimer(); m_timer.Tick += new EventHandler(f_timer);//подписка на событие таймера m_timer.Interval = new TimeSpan(0, 0, 1);//интервал вызова таймера m_timer.Start(); m_flag = true;//запускаем поток логически System.Threading.Thread t = new System.Threading.Thread(f_thread); t.IsBackground = true; //запрещаем поток в фоновом режиме t.Start(); } private void f_timer(object sender, EventArgs e) { //обновляем TextBox textBox.Text = Convert.ToString(m_count, 10); } //функция потока private void f_thread() { //блокируем m_count lock (m_thisLock) { while (m_flag) { //делаем задержку System.Threading.Thread.Sleep(TimeSpan.FromSeconds(0.1)); m_count++; } } m_timer.Stop();//останавливаем таймер MessageBox.Show("end potok"); } //функция останавливает поток private void button1_Click(object sender, RoutedEventArgs e) { m_flag = false; } } } |
Регулярные выражения
Почитать можно тут.
1 2 3 4 5 6 7 8 9 10 11 |
//регулярное выражение Regex regex = new Regex("Я фрилансер\\s*</a>", RegexOptions.IgnoreCase); Match match = regex.Match(text);//получаем все совпадения if (match.Success) { MessageBox.Show("naideno = "+match.Groups[0].Value+" g1= "+match.Groups[1].Value); } else { MessageBox.Show("not found"); } |
Динамические массивы ArrayList
почитать можно тут.
1 2 3 4 5 6 7 8 9 |
ArrayList arr = new ArrayList(); arr.Add("hellow"); arr.Add(1); arr.Add("0.100"); for(int i=0;i<arr.Count;i++) { MessageBox.Show(arr[i].ToString()); } |
Динамические массивы List — аналог vector в C++
1 2 3 4 5 6 7 8 9 10 |
List<string> arr = new List<string>(); arr.Add("hellow"); arr.Add("1"); arr.Add("0.100"); arr[2] = "10"; for(int i=0;i<arr.Count;i++) { MessageBox.Show(arr[i]); } |
Сделать кнопку неактивной и поля прокрутка вниз
1 2 3 |
button1.IsEnabled = false; textBox.IsEnabled = false; textBox.ScrollToEnd();//прокрутка вниз |
Изменить иконку
Добавляем иконку в Проект -> Свойство
Если не отображается, то можно добавить в коде
1 |
Icon="icontexto-inside-furl_5766.ico" |