[[:oktatas:programozás:csharp|< CSharp]] ====== GUI példák ====== ===== Címke ===== using System; using System.Drawing; using System.Windows.Forms; class ablak : Form { Label cimke1; ablak() { cimke1 = new Label(); cimke1.Text = "Valami"; //Igazítás: cimke1.TextAlign = ContentAlignment.MiddleCenter; // Lehetséges értékek: TopLeft; TopCenter; TopRight; MiddleLeft; //MiddleCenter; Middleright;BottomLeft; BottomCenter; BottomRight //Szegély: cimke1.BorderStyle = BorderStyle.FixedSingle; //None; FixedSingle;Fixed3D cimke1.Width = 100; cimke1.Height = 100; cimke1.Top = 200; cimke1.Left = 200; Height = 480; Width = 600; Show(); Controls.Add(cimke1); } static void Main() { Application.Run(new ablak()); } } ===== Menü, vágólap használat ===== using System; using System.Drawing; using System.Windows.Forms; class Program : Form { MainMenu fomenu; MenuItem menupontFajl; MenuItem menupontSzerkesztes; MenuItem menupontBeilleszt; MenuItem menupontMasol; TextBox textBox1; Program() { Width=800; Height=600; textBox1 = new TextBox(); fomenu = new MainMenu(); menupontFajl = new MenuItem(); menupontSzerkesztes = new MenuItem(); menupontBeilleszt = new MenuItem(); menupontMasol = new MenuItem(); textBox1.Multiline = true; textBox1.Dock = DockStyle.Fill; textBox1.ScrollBars = ScrollBars.Vertical; textBox1.AcceptsTab = true; textBox1.AcceptsReturn = true; fomenu.MenuItems.Add(menupontFajl); fomenu.MenuItems.Add(menupontSzerkesztes); menupontFajl.Text = "Fájl"; menupontSzerkesztes.Text = "Szerkesztés"; menupontSzerkesztes.MenuItems.Add(menupontBeilleszt); menupontSzerkesztes.MenuItems.Add(menupontMasol); menupontBeilleszt.Text = "Beillesztés"; menupontBeilleszt.Click += new EventHandler(Menu_Paste); menupontBeilleszt.Shortcut = Shortcut.CtrlV; menupontMasol.Text = "Másol"; menupontMasol.Click += new EventHandler(Menu_Copy); Controls.Add(textBox1); Menu = fomenu; } static void Main() { Application.Run(new Program()); } private void Menu_Copy(object sender, EventArgs e) { // Nézzük meg, hogy van-e szöveg kiválasztva a szövegdobozban if(textBox1.SelectionLength > 0) // A válgólapra másoljuk a kiválasztott szöveget textBox1.Copy(); } private void Menu_Cut(object sender, EventArgs e) { // Nézzük meg, hogy van-e szöveg kiválasztva a szövegdobozban if(textBox1.SelectedText != "") // Kivágjuk a szöveget a szövegdobozból és a vágólapra másoljuk textBox1.Cut(); } private void Menu_Paste(object sender, EventArgs e) { // Ha van szöveg a vágólapon, akkor beillesztjük if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true) { // Ha van kiválasztott szöveg a szövegdobozban if(textBox1.SelectionLength > 0) { // Megkérdezzük felül akarja-e írni a kiválasztott szöveget. if(MessageBox.Show("Lecseréled a kiválsztott szöveget beillesztéssel?", "Beillesztés példa", MessageBoxButtons.YesNo) == DialogResult.No) // Az aktuális kijelölés után visszük a kurzort és beillesztéshez textBox1.SelectionStart = textBox1.SelectionStart + textBox1.SelectionLength; } // Beillesztjük a vágólap szövegét a szövegdobozba textBox1.Paste(); } } private void Menu_Undo(object sender, System.EventArgs e) { // Megvizsgáljuk engedélyezett-e a visszavonás if(textBox1.CanUndo == true) { // Visszavonás textBox1.Undo(); // Töröljük a visszavonás tárolóból az utolsó műveletet textBox1.ClearUndo(); } } } ===== Szál készítés ===== Az alábbi példában egy gombnyomásra egy külön szál indul, amely vár 5 másodpercig, majd feldob egy üzenetablakot. Szálak nélkül a "Kiír" gomb az 5 másodperc alatt használhatatlan lenne. using System; using System.Drawing; using System.Windows.Forms; using System.Threading; class Program : Form { Button StartButton; Button KiirButton; Program() { StartButton = new Button(); KiirButton = new Button(); StartButton.Location = new Point(200, 200); StartButton.Text = "Start"; StartButton.Click += new EventHandler(StartButton_Click); KiirButton.Location = new Point(400, 200); KiirButton.Text = "Kiir"; KiirButton.Click += new EventHandler(KiirButton_Click); Controls.Add(StartButton); Controls.Add(KiirButton); Width = 800; Height = 600; CenterToScreen(); } private void StartButton_Click(object sender, EventArgs e) { Thread thread1 = new Thread(new ThreadStart(fut)); thread1.Start(); } private void KiirButton_Click(object sender, EventArgs e) { MessageBox.Show("Kiír árnyék"); } private void fut() { Thread.Sleep(5000); MessageBox.Show("Kivártuk"); } public static void Main() { Application.Run(new Program()); } } ===== Időzítő ===== ==== System.Windows.Forms.Timer időzítő ==== Célunk, hogy 5 másodperc múlva egy üzenetablak jelenjen meg. Ezt a System.Windows.Forms.Timer osztállyal tesszük meg: using System; using System.Drawing; using System.Windows.Forms; class Program : Form { Button StartGomb; System.Timer timer1; Program() { StartGomb = new Button(); timer1 = new Timer(); timer1.Tick += new EventHandler(Ido_Tick); timer1.Interval = 5000; StartGomb.Text = "Start"; StartGomb.Location = new Point(200,200); StartGomb.Click += new EventHandler(StartGomb_Click); Controls.Add(StartGomb); Width = 800; Height = 600; } private void StartGomb_Click(object sender, EventArgs e) { timer1.Start(); } private void Ido_Tick(object sender, EventArgs e) { MessageBox.Show("Idő van"); timer1.Stop(); } public static void Main() { Application.Run(new Program()); } } Az üzenet ablak után az időzítőt kikapcsoljuk. A gomb lenyomására bármikor újraindítható. ==== Más időzítők ==== Van két másik időzítő a .Net keretrendszerben: System.Timers.Timer System.Threading.Timer ==== Adott időpontban szeretnénk tenni valamit ==== using System; using System.Drawing; using System.Windows.Forms; class Program : Form { Timer timer1; Label label1; Program() { timer1 = new Timer(); label1 = new Label(); timer1.Interval = 1000; timer1.Tick += new EventHandler(Timer1_Tick); label1.Location = new Point(200, 200); Controls.Add(label1); //~ Load += new EventHandler(Form1_Load); Load += Form1_Load; Width = 800; Height = 600; } private void Form1_Load(object sender, EventArgs e) { timer1.Start(); } private void Timer1_Tick(object sender, EventArgs e) { int hour = DateTime.Now.Hour; int minute = DateTime.Now.Minute; string TimeString = hour + ":" + minute; label1.Text = TimeString; if(TimeString == "8:17") { timer1.Stop(); MessageBox.Show("Idő van"); } } public static void Main() { Application.Run(new Program()); } } ===== Nyomtatás ===== using System; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms; using System.IO; class Program : Form { private Button printButton; private Font printFont; PrintDialog printDialog1; PrintDocument pd; Program() { printButton = new Button(); printFont = new Font("Arial", 24); printDialog1 = new PrintDialog(); pd = new PrintDocument(); printDialog1.Document = pd; printButton.Text = "Nyomtatás"; printButton.Location = new Point(100, 100); printButton.Click += new EventHandler(Printbutton_Click); Controls.Add(printButton); Width = 800; Height = 600; } private void Printbutton_Click(object sender, EventArgs e) { /* Ez a rész kihagyható, ha az alapértelmezett nyomtatóra nyomtatunk */ /**********************************************************************/ printDialog1.ShowDialog(); string printer = printDialog1.PrinterSettings.PrinterName; pd.PrinterSettings.PrinterName = printer; /**********************************************************************/ pd.PrintPage += new PrintPageEventHandler(pd_PrintPage); pd.Print(); } private void pd_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; // Oldalszámok számítása linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); line = "Valami hossabb szöveg őőűűű"; yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); line = null; // Ha több soros, másik oldalt is nyomtatunk if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; } public static void Main() { Application.Run(new Program()); } } Nyomtatásról még több info: * http://msdn.microsoft.com/en-us/library/xdt36c58.aspx * http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx ===== Több ablak ===== ==== Egyszerűen két ablak ==== Az alábbiakban egy kétablakos program kerül bemutatásra: using System; using System.Drawing; using System.Windows.Forms; class menuablak : Form { Button gomb = new Button(); Label cimke = new Label(); ablak masikablak = new ablak(); menuablak() { gomb.Text = "Első menü"; gomb.Location = new Point (112, 50); gomb.Click += new EventHandler(Gomb_Click); Controls.Add(gomb); cimke.Text = "Progim"; cimke.Location = new Point(112, 10); Controls.Add(cimke); } static void Main() { Application.Run(new menuablak()); } void Gomb_Click(object sender, EventArgs e) { masikablak.Show(); } } public class ablak : Form { Button gomb = new Button(); Label cimke = new Label(); public ablak() { gomb.Text = "Bezár"; gomb.Location = new Point (112, 150); gomb.Click += new EventHandler(Gomb_Click); Controls.Add(gomb); cimke.Text = "Progim"; cimke.Location = new Point(112, 10); Controls.Add(cimke); } void Gomb_Click(object sender, EventArgs e) { this.Hide(); } } ==== Az ablakok közötti adatátvitel ==== class Program : Form { Button propertiesButton; static Label label1; public static string LabelFelirat { set{ label1.Text = value; } } Program() { propertiesButton = new Button(); label1 = new Label(); label1.Text = "Első"; label1.Location = new Point(200, 100); propertiesButton.Text = "Tulajdonságok"; propertiesButton.Location = new Point(400, 400); propertiesButton.Click += new EventHandler(PropertiesButton_Click); Controls.Add(propertiesButton); Controls.Add(label1); Width = 800; Height = 600; } private void PropertiesButton_Click(object sender, EventArgs e) { Properties propertiesWindow = new Properties(); propertiesWindow.ShowDialog(); label1.Text = propertiesWindow.getFelirat(); propertiesWindow.Dispose(); } public static void Main() { Application.Run(new Program()); } } statikus tagokkal: using System; using System.Drawing; using System.Windows.Forms; class Properties : Form { Button changeButton; public Properties() { changeButton = new Button(); changeButton.Text = "Cseréld"; changeButton.Location = new Point(200,200); changeButton.Click += new EventHandler(ChangeButton_Click); Controls.Add(changeButton); Width = 600; Height = 480; } private void ChangeButton_Click(object sender, EventArgs e) { Program.LabelFelirat = "Valami"; } } class Program : Form { Button propertiesButton; static Label label1; Properties propertiesWindow; public static string LabelFelirat { set{ label1.Text = value; } } Program() { propertiesButton = new Button(); propertiesWindow = new Properties(); label1 = new Label(); label1.Text = "Első"; label1.Location = new Point(200, 100); propertiesButton.Text = "Tulajdonságok"; propertiesButton.Location = new Point(400, 400); propertiesButton.Click += new EventHandler(PropertiesButton_Click); Controls.Add(propertiesButton); Controls.Add(label1); Width = 800; Height = 600; } private void PropertiesButton_Click(object sender, EventArgs e) { propertiesWindow.ShowDialog(); } public static void Main() { Application.Run(new Program()); } } ===== Tray ikon ===== ==== Csak tray ikon ==== using System; using System.Drawing; using System.Windows.Forms; public class Program : Form { private NotifyIcon trayIcon; private ContextMenu trayMenu; public Program() { // Egy egyszerű tary menü készítése egy elemmel trayMenu = new ContextMenu(); trayMenu.MenuItems.Add("Exit", OnExit); // Készítünk egy tray ikont. A példában a rendszer egyik // ikonját használjuk, de használható saját ikon is trayIcon = new NotifyIcon(); trayIcon.Text = "Tray programom"; trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40); // A traeIcon objektumhoz hozzáadjuk a menüt trayIcon.ContextMenu = trayMenu; trayIcon.Visible = true; } protected override void OnLoad(EventArgs e) { Visible = false; // Az ablak elrejtése ShowInTaskbar = false; // A tasklistán nem látható base.OnLoad(e); } private void OnExit(object sender, EventArgs e) { Application.Exit(); } protected override void Dispose(bool isDisposing) { if (isDisposing) { //Töröljük az ikon objektumot trayIcon.Dispose(); } base.Dispose(isDisposing); } [STAThread] public static void Main() { Application.Run(new Program()); } } ==== Felnyíló ablakkal ==== using System; using System.Drawing; using System.Windows.Forms; public class Program : Form { NotifyIcon trayIcon; ContextMenu trayMenu; public Program() { trayMenu = new ContextMenu(); trayIcon = new NotifyIcon(); // Egy egyszerű tary menü készítése egy elemmel trayMenu.MenuItems.Add("Exit", OnExit); trayMenu.MenuItems.Add("Open", OnOpen); // Készítünk egy tray ikont. A példában a rendszer egyik // ikonját használjuk, de használható saját ikon is trayIcon.Text = "Tray programom"; trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40); trayIcon.ContextMenu = trayMenu; trayIcon.Visible = true; Resize += new EventHandler(Form1_Resize); } protected override void OnLoad(EventArgs e) { Visible = false; // Az ablak elrejtése ShowInTaskbar = false; // A tasklistán nem látható base.OnLoad(e); } private void OnExit(object sender, EventArgs e) { Application.Exit(); } private void OnOpen(object sender, EventArgs e) { Show(); WindowState = FormWindowState.Normal; } private void Form1_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) { Hide(); ShowInTaskbar = false; } } protected override void Dispose(bool isDisposing) { if (isDisposing) { //Töröljük az ikon objektumot trayIcon.Dispose(); } base.Dispose(isDisposing); } [STAThread] public static void Main() { Application.Run(new Program()); } } ==== Rendszerikonokkal ==== using System; using System.Drawing; using System.Windows.Forms; class Program : Form { NotifyIcon ni; Button button1; Program() { ni = new NotifyIcon(); button1 = new Button(); ni.BalloonTipTitle = "Cím"; ni.BalloonTipText = "Elindult az emlékeztető ikon"; ni.BalloonTipIcon = ToolTipIcon.None; /* ToolTipIcon.Info, ToolTipIcon.Error, ToolTipIcon.Warning, ToolTipIcon.None */ ni.Text = "Emlékeztető"; //~ ni.Icon = new Icon(SystemIcons.Application, 40, 40); ni.Icon = SystemIcons.Application; /* SystemIcons.Hand behajtani tilos alakzat SystemIcons.Exclamation egyéb veszély tábla SystemIcons.Asterisk villanykörte SystemIcons.Application állatfej SystemIcons.Error behajtani tilos SystemIcons.Information villanykörte SystemIcons.Question kérdőjel SystemIcons.Warning egyéb veszély tábla SystemIcons.WinLogo állatfej */ button1.Text = "Ikonba"; button1.Location = new Point(200,200); button1.Click += new EventHandler(Button1_Click); Controls.Add(button1); Width = 800; Height = 600; } private void Button1_Click(object sender, EventArgs e) { ni.Visible = true; ni.ShowBalloonTip(5); } public static void Main() { Application.Run(new Program()); } } ==== Variáció ==== using System; using System.Drawing; using System.Windows.Forms; class Program : Form { NotifyIcon ni; Button button1; Program() { ni = new NotifyIcon(); button1 = new Button(); ni.BalloonTipTitle = "Cím"; ni.BalloonTipText = "Elindult az emlékeztető ikon"; ni.BalloonTipIcon = ToolTipIcon.Info; ni.Text = "Emlékeztető"; ni.Icon = SystemIcons.Application; ni.DoubleClick += new EventHandler(Notifyicon_DoubleClick); button1.Text = "Ikonba"; button1.Location = new Point(200,200); button1.Click += new EventHandler(Button1_Click); Controls.Add(button1); Width = 800; Height = 600; } private void Notifyicon_DoubleClick(object sender, EventArgs e) { //Mi történjen duplakattintásra } private void Button1_Click(object sender, EventArgs e) { ni.Visible = true; //~ ni.ShowBalloonTip(5); ni.ShowBalloonTip(3000, "Teszt alkalmazás", "Ez a program még nincs bezárva \n\n"+ "tray állapotban van\n"+ "Jobb klikk a kilépéshez", ToolTipIcon.Info); } public static void Main() { Application.Run(new Program()); } } ===== Folyamatok listázása ===== using System; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; class Program : Form { Process[] p; ListBox plist; Program() { plist = new ListBox(); p = Process.GetProcesses(); plist.Location = new Point(100, 50); plist.Size = new Size(300, 400); for(int i=0; i ===== Táblázat és Access adatbázis ===== Adott egy bolt.accdb adatbázis, egy Szemely nevű táblával. A Szemely tábla a következő mezőket és értékeket tartalmazza: ^az^nev^telepules^fizetes^szuletes^ |1| Nagy Sándor | Szolnok | 560000 | 1975.05.05. | |2| Éber Lajos | Debrecen | 440000 | 1978.02.01 | |3| Kék János | Szolnok | 350000 | 1982.08.02 | Olyan programot írunk, az adatbázis Szemely tábláját olvasva, egy táblázatban (DataGridView) jeleníti azokat meg. using System; using System.Drawing; using System.Windows.Forms; using System.Data.OleDb; class Program : Form { DataGridView tabla; string ks; //Kapcsolat sztring string sql; //Lekérdezés Program() { tabla = new DataGridView(); //A táblázat tulajdonságai tabla.ColumnCount = 5; tabla.RowCount = 8; tabla.Size = new Size(700, 400); tabla.RowHeadersVisible = true; for(int i=0; i<5; i++) tabla.Columns[i].Width = 100; tabla.Columns[0].Name = "Az"; tabla.Columns[1].Name = "Név"; tabla.Columns[2].Name = "Település"; tabla.Columns[3].Name = "Fizetés"; tabla.Columns[4].Name = "Születés"; //A kapcsolat felépítése ks = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=bolt.accdb"; OleDbConnection kap = new OleDbConnection(ks); sql = "SELECT * FROM Szemely"; OleDbCommand par = new OleDbCommand(sql, kap); //Kapcsoalt megnyitása kap.Open(); //A lekérdezés futtatása OleDbDataReader adat = par.ExecuteReader(); //Az egyes rekordokat végigvesszük, és táblázatba rakjuk int j=0; while(adat.Read()) { tabla.Rows[j].Cells[0].Value = adat.GetValue(0); tabla.Rows[j].Cells[1].Value = adat.GetValue(1); tabla.Rows[j].Cells[2].Value = adat.GetValue(2); tabla.Rows[j].Cells[3].Value = adat.GetValue(3); tabla.Rows[j].Cells[4].Value = adat.GetValue(4); j++; } kap.Close(); //Az ablak tulajdonságai Controls.Add(tabla); Width=800; Height=600; } static void Main() { Application.Run(new Program()); } } ===== Bezárás esemény kezelése ===== using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; public class Program : Form { public Program() { Closing += new CancelEventHandler(AuthForm_Closing); CenterToScreen(); Width = 300; Height = 200; } protected void AuthForm_Closing(object sender, CancelEventArgs e) { DialogResult dr = MessageBox.Show("Biztosan be akarod zárni?", "Kilépés esemény!", MessageBoxButtons.YesNo); if (dr == DialogResult.No) e.Cancel = true; else e.Cancel = false; } public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Program()); } } ===== Azonosítás ===== using System; using System.Drawing; using System.Windows.Forms; class Program : Form { Program() { CenterToScreen(); Width = 800; Height = 600; } public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (PerformLogin()) Application.Run(new Program()); } static bool PerformLogin() { using (AuthForm authform = new AuthForm()) { if (authform.ShowDialog() == DialogResult.OK) { if(AuthenticateUser(authform.UserName, authform.Password)) return true; else { MessageBox.Show("Azonosítás sikertelen"); return false; } } else return false; } } static bool AuthenticateUser(String user, String pass) { //Ide jön az azonosítás return true; } } public class AuthForm : Form { Label label = new Label(); Button loginButton = new Button(); public String UserName; public String Password; public AuthForm() { label.Text = "Azonosítás"; label.Location = new Point(50, 10); label.Size = new Size(100, 30); loginButton.Text = "Belépés"; loginButton.Location = new Point(50, 150); loginButton.Click += new EventHandler(LoginButton_Click); Controls.Add(label); Controls.Add(loginButton); TopMost = true; CenterToScreen(); Width = 300; Height = 200; } protected void LoginButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } }