I am dealing with a new project. I have a class to draw Rectangles to windows form. I want to embed this class to another class. Code's below;
Main Code will call the shape code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using sekilciz_uygulama;
namespace xml_test_v1
{
class Program
{
static void Main(string[] args)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("c:\\sw_xml_test_4.xml");
int rad=0;
string giris_text = Console.ReadLine().ToString();
Console.WriteLine(giris_text);
foreach(XmlNode node in xDoc.SelectNodes("network/switch"))
{
string ip_adress = node.SelectSingleNode("ip_adress").InnerText.ToString();
Console.WriteLine(ip_adress);
if (ip_adress.Contains(giris_text))
{
// call for shape code!!!
}
}}}}
Code for Creating Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace sekilciz_uygulama
{
public class Sekilciz
{
public Rectangle[] skare;
private SolidBrush firca;
private int x,y, genislik, yukseklik;
public Sekilciz()
{
skare = new Rectangle[5];
firca = new SolidBrush(Color.Blue);
x = 500;
y = 200;
genislik= 100;
yukseklik =100;
for(int i=0; i< skare.Length;i++)
{
skare[i] = new Rectangle(x,y,genislik,yukseklik);
x-=150;
}
}
public void kareciz(Graphics duzlem)
{
foreach(Rectangle rec in skare)
{
duzlem.FillRectangle(firca,rec);
}
}
}
}
var sekilciz = new Sekilciz();
sekilciz.kareciz(null);
You need to pass a parameter to your method kareciz
// "this" is your windows form, or control like button
var myGraphic = this.CreateGraphics();
var sekilciz = new Sekilciz(myGraphic);
sekilciz.kareciz();
But you have too many processing going on in your constructor. It is better to move that code in some other method in the same class.
Look here to complete sample on drawing on windows form:
The Basics of Drawing Graphics onto Windows Forms
Related
Just started learning Visual Studio and I'm trying to make a soundboard in Windows Forms.
ButtonMaker(); is the function I use to make a button for each soundfile in my directory so I don't have to make 70 different buttons for every sound, but when I run the program nothing shows up in the forms window. Anybody know why? I've tried calling the function in Main() and in the initial Form1 class but nothing happens in either. Forms class file here:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MySoundBoard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
///Tried running it here
}
private void Form1_Load(object sender, EventArgs e)
{
///Tried running it here
}
private void ButtonMaker()
{
string[] files = Soundfiles.GetFile();
foreach (var item in files)
{
string btnName = item.ToUpper();
Button btNname = new Button();
btNname.Text = item;
int x = 40;
int y = 40;
btNname.Location = new Point(x, y);
x = x + 50;
if (x>900)
{
x = 40;
y = y + 30;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Here is the SoundFiles class:
using System.IO;
using System;
using System.Text;
using System.Diagnostics;
using WMPLib;
namespace MySoundBoard
{
class Soundfiles {
WMPLib.WindowsMediaPlayer Player;
static public string[] GetFile() {
string txtPath = #"C:\Documents\path\to\sound effects";
string[] files =
Directory.GetFiles(txtPath, "*ProfileHandler.cs", SearchOption.TopDirectoryOnly);
return files;
}
public void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.URL = url;
Player.controls.play();
}
}
}
And the main project file(not that worked with yet):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MySoundBoard
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
///Tried running it here
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
As said, I'm very new to this language and any help would be appriciated!
You create the buttons but never add them to the form. Just add
this.Controls.Add(btNname);
The next thing is, that your buttons will not do something. You'll need to add an event handler as well.
btNname.Click += ...;
In order to know which button plays which sound, you need to find a way to have that association. A hacky approach is
btNname.Tag = item;
and then evaluate Tag later
(I am very new to C#) I am creating a forms application, and the purpose is to get a string from a Web API, then put that text onto a label. I have successfully gotten the data from the Web, but when I try to update the label, I have no luck.
I have debugged and found that my method inside my class Is executing, but just not setting the label's text. As you can see below, I tried to use this.resultLabel.text = str;. Here's the classes:
Program.cs (not the form cs file)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net;
using System.IO;
namespace WebsiteAPITest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
class PostManager
{
public void setupClient()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://yakovliam.com/phpApi/csTest.php"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string respStr;
using (Stream stream = WebResp.GetResponseStream()) //modified from your code since the using statement disposes the stream automatically when done
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
respStr = reader.ReadToEnd();
}
MessageBox.Show(respStr);
Form1 form = new Form1();
form.SetResultLabel(respStr);
}
}
}
Actual form class (Form1.cs)
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 WebsiteAPITest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void GetButton_Click(object sender, EventArgs e)
{
PostManager postManager = new PostManager();
postManager.setupClient();
}
public void SetResultLabel(string str)
{
this.resultLabel.Text = str;
this.resultLabel.Refresh();
}
}
proof of label name:
Inside setupClient you call Form1 form = new Form1(); that creates a second Form1 which you never display, then you call SetResultLabel(respStr) inside this second form you never display, then you leave the method and discard it.
If you want to call SetResultLabel of your calling form, you have to pass the calling form to setupClient:
public void setupClient(Form1 callingForm)
{
...
callingForm.SetResultLabel(respStr);
Then inside your Form1:
postManager.setupClient(this);
It's quite dangerous to pass forms to other methods; a better design is to have the other method return data to your form:
public string setupClient()
{
...
return respStr;
}
And inside Form1:
SetResultLabel(postManager.setupClient());
Hi I'm practicing using winform MVP pattern in C#.
I made Models, Presenters and Views folders, and they has a each class.
(Models has Data.cs, Presenters has Datapresenter.cs and View have interface.cs and Form.cs)
I used 'FlowLayoutPanel'. and I made Label to make numbers. Like this.
My progress so far.
Here is Data.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LayoutSample.Models
{
public class Data
{
public string label { get; set; }
public string CalculateArea()
{
return label;
}
}
}
Here is DataPresenter.cs (Presenter)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using LayoutSample.Models;
using LayoutSample.Views;
namespace LayoutSample.Presenters
{
public class DataPresenter
{
IFlowLabel LabelView;
public DataPresenter(IFlowLabel view)
{
LabelView = view;
}
public void CalculateArea()
{
Data data = new Models.Data();
data.label = string.Copy(LabelView.label);
var th = new Thread(() =>
{
for (int i = 0; i < 100; i++)
{
Label label = new Label();
Panel flowLayoutPanel1 = new Panel();
label.Text = i.ToString();
flowLayoutPanel1.Controls.Add(label);
Thread.Sleep(10);
}
});
th.Start();
}
}
}
Here is interface.cs(View)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LayoutSample.Views
{
public interface IFlowLabel
{
string label { get; set; }
}
}
and this is Form.cs
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;
using LayoutSample.Models;
using LayoutSample.Presenters;
using LayoutSample.Views;
namespace LayoutSample
{
public partial class Form1 : Form, IFlowLabel
{
public Form1()
{
InitializeComponent();
}
string IFlowLabel.label
{
get
{
return flowLayoutPanel1.ToString();
}
set
{
if (flowLayoutPanel1.InvokeRequired)
{
flowLayoutPanel1.Invoke(new MethodInvoker(() =>
{
flowLayoutPanel1.Text = value;
}));
}
else
{
flowLayoutPanel1.Text = value;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
Label label = new Label();
label.AutoSize = false;
label.Width = 50;
label.Text = i.ToString();
flowLayoutPanel1.Controls.Add(label);
}
DataPresenter presenter = new DataPresenter(this);
presenter.CalculateArea();
}
}
}
From here, I want to make the numbers increasing.
How could I increase them at same time?
p.s
I've changed DataPresenter.cs
I've chagned public void Calculate Area() to
public void CalculateArea()
{
Data data = new Models.Data();
data.label = string.Copy(LabelView.label);
var th = new Thread(() =>
{
for ( int i = 1; i < 101; i++)
{
for (int j=1; j<101;j++)
{
Label label = new Label();
label.Text = j.ToString();
Console.WriteLine(label);
}
Thread.Sleep(1000);
}
});
th.Start();
}
I can watch the numbers increasing via console, but I can't see the change in WimForm. How can I bring the increment to WinForm??
I'm making a simple application to simulate the bankteller problem.
What I'm trying to simulate is:
You have 4 counters in a store. 1 counter is open. Customers start coming in and enter the line for the first counter.
When the fourth customer enters the line for the first counter, another counter should open. The line should be equally divided between the 2 counters.When the customer at the second counter is helped and no new customers enter the line, the counter should close. Basically 4 is too many.
I can't seem to figure it out. I know I need to use a queue. But how? Could someone give me an example in console application? Preferable C#.
Thanks in advance.
Here is what I tried so far,
register class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class Register
{
private int customerCount;
public Queue<Customer> Line = new Queue<Customer>();
public Register()
{
customerCount = 2;
}
public Register(int customerCount)
{
this.customerCount = customerCount;
}
public int getCustomers()
{
return customerCount;
}
}
}
Customer class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class Customer
{
private int checkoutTime;
public Customer()
{
checkoutTime = 3;
}
public Customer(int checkoutTime)
{
this.checkoutTime = checkoutTime;
}
public int GetCheckoutTime()
{
return checkoutTime;
}
}
}
Register manager:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class RegisterManager
{
public List<Register> registers = new List<Register>();
Register r1 = new Register();
Customer c1 = new Customer();
public RegisterManager()
{
registers.Add(r1);
}
public void ManageCustomers()
{
for (int i = 0; i < registers.Count; i++)
{
registers.Insert(i, new Register());
if (i / 4 <= registers..Line.Count)
{
}
}
}
}
}
I want to create a method which makes my application wait X number of seconds, then continues on down a line of scripts. For example, this is the code that I have so far, after reading many similar help topics:
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
methods.WriteTextToScreen(label1, "Hello!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Welcome!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Allo!");
}
public class methods
{
public static int timeSlept;
public static void WriteTextToScreen(Label LabelName, string text)
{
LabelName.Text = text;
}
public static void sleepFor(int seconds)
{
timeSlept = 0;
System.Timers.Timer newTimer = new System.Timers.Timer();
newTimer.Interval = 1000;
newTimer.AutoReset = true;
newTimer.Elapsed += new System.Timers.ElapsedEventHandler(newTimer_Elapsed);
newTimer.Start();
while (timeSlept < seconds)
{
Application.DoEvents();
}
Application.DoEvents();
}
public static void newTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timeSlept = IncreaseTimerValues(ref timeSlept);
Application.DoEvents();
}
public static int IncreaseTimerValues(ref int x)
{
int returnThis = x + 1;
return returnThis;
}
}
}
}
What I want to do is have my program do the methods.WriteTextToScreen(label1, "Hello!")
then wait for 1 second, then continue on in the same fashion. The problem is that the Form I'm displaying the text on doesn't show up at all until it has written "Allo!" onto the screen, so the first time it appears it already says that. Am I doing something wrong, or is there just no way to do this?
The form doesn't show until it has been constructed i.e. all the code in Form1 is run. See here for info on form constructors: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.form.aspx
To fix your problem you could move the writeTextToScreen and sleep code into the forms on load method. See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onload.aspx