|
I'm new to C# and have been reading up on Classes. In my small app, I want to instantiate a class called 'backupJob'. There are two operationType members: local to remote server and syncing both ways. I want to create an object for one op type and then create another object for the other type.
In the demos I have seen they always show this:
Car myCar1 = new Car();
Car myCar2 = new Car();
I may end up with more than two backup jobs so I'm thinking there must be a better way to manage the object names besides myCar1 and myCar2, etc. I will want to delete an object as well as create more objects so is it best to keep track of these objects in an Array or possibly a Collection?
Thanks...
|
|
|
|
|
Create and maintain objects in a collection (list maybe). You can add and remove objects as required from within the list.
|
|
|
|
|
As Abhinav suggests, a collection is the easiest way to go: declare it as class level as a private List and you can do what you want with it:
private List<Car> myCars = new List<Car>();
...
Car car = new Car();
car.Color = blue;
car.Fuel = Fuels.Diesel;
myCars.Add(car);
...
myCars.Remove(car);
...
foreach (Car car in myCars)
{
car.Respray(Color.Red);
}
This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre.
Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.
|
|
|
|
|
Thanks for the help...!!!
|
|
|
|
|
You're welcome!
This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre.
Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.
|
|
|
|
|
How to set a textbox on a website automatically which is inside an iframe or a frame?
I need the C# code for a simple text box
|
|
|
|
|
|
How can I add (include) c libraries that is not available in windows or in my project?
|
|
|
|
|
|
Sorry for the not so descriptive or apt title but I have been trying to do this for a while now but to no effect and its getting to me. I have a chat server(console application) and a chat client (winform application) and a separate winform application which only has a button on it. Whenever there is any new message and if the client window is minimized then i want that the button on that separate winform turns red. Once the client window gets restored or maximized then it should turn back to yellow which is also the original color of the button. I am able to achieve the change of color when a message is received but not taking into consideration the minimized state etc. If i try to do that using IsIconic nothing happens. What i have done is that get a handle of the client winform in the server application and checking if it is Iconic or not. Please guide as i am stuck on this for a while. The code is as follows:
The Server Application:
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Net;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();
public static void Main()
{
string mutex_id = "MY_APP";
using (Mutex mutex = new Mutex(false, mutex_id))
{
if (!mutex.WaitOne(0, false))
{
return;
}
var loaclAddress = IPAddress.Parse("127.0.0.1");
var serverSocket = new TcpListener(loaclAddress, 81);
/*
TcpListener serverSocket = new TcpListener(8888);
*/
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClinet
{
//This is used to send custom message to your Winforms
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
//This is used to find your winforms window
[DllImport("user32", CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string className, string windowName);
//This is used to register custom message so that it's ensured to be unique
[DllImport("user32")]
private static extern int RegisterWindowMessage(string msgName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsIconic(IntPtr hWnd);
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
int msg = 0;
IntPtr hwnd = IntPtr.Zero;
int red = RegisterColorCode(Color.Red);
//Console.WriteLine(red);
int yellow = RegisterColorCode(Color.Yellow);
//Console.WriteLine(yellow);
msg = 49806;
if (hwnd == IntPtr.Zero)
hwnd = FindWindow(null, "Winforms Application");
IntPtr hwnd1 = FindWindow(null, "ClientApp");
if (IsIconic(hwnd1)) //this if-else seems to have no effect as no color changes in the button on the winform
{
if (hwnd != IntPtr.Zero)
SetBackColor(hwnd, msg);
}
else
{
msg = 50054;
SetBackColor(hwnd, msg);
}
//SetBackColor(hwnd, msg);
//If i write only this then color changes but not on minized state its changed once and for all...
//what i want is for the previous if else condition to work**
hwnd1 = IntPtr.Zero;
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
hwnd = IntPtr.Zero;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
static int RegisterColorCode(Color c)
{
return RegisterWindowMessage(c.ToString());
}
static void SetBackColor(IntPtr hwnd, int colorCode)
{
SendMessage(hwnd, colorCode, IntPtr.Zero, IntPtr.Zero);
}
} //end class handleClinet
}//end namespace
The Client Application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
namespace chatClient
{
public partial class Form1 : Form
{
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream;//new NetworkStream(clientSocket); //default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
Text = "ClientApp";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
private void button2_Click(object sender, EventArgs e)
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 81);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
button2.Enabled = false;
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
The Winform Apllication which has the button on it:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace consoleMR
{
public partial class Form1 : Form
{
[DllImport("user32")]
private static extern int RegisterWindowMessage(string msgName);
int red, yellow;
public Form1()
{
InitializeComponent();
red = RegisterColorCode(Color.Red);
yellow = RegisterColorCode(Color.Yellow);
//Set your form caption to a specified (must be unique at the time it runs)
Text = "Winforms Application";
}
private int RegisterColorCode(Color c)
{
return RegisterWindowMessage(c.ToString());
}
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MINIMIZE = 0xf020;
private const int SC_MAXIMIZE = 0xf030;
private const int SC_RESTORE = 0xF120;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SYSCOMMAND)
{
if (m.WParam.ToInt32() == SC_MAXIMIZE || m.WParam.ToInt32() == SC_RESTORE)
{
button1.BackColor = Color.Yellow;
this.WindowState = FormWindowState.Maximized;
return;
}
}
switch (m.Msg)
{
case 49806:
button1.BackColor = Color.Red;
return;
case 570445:
button1.BackColor = Color.Yellow;
return;
}
base.WndProc(ref m);
}
private void buttonUCT_Click(object sender, EventArgs e)
{
Process.Start("C:\\Users\\MainUser\\Documents\\Visual Studio 2010\\Projects\\chatServer\\chatServer\\bin\\Debug\\chatServer.exe");
}
}
}
I have been stuck on this for a while now and would really appreciate any help or sample code or correction of code...really anything at all
|
|
|
|
|
I don't think anyone is going to look at that code until it is edited, properly indented and placed between <pre> tags like:
private void buttonUCT_Click(object sender, EventArgs e)
{
Process.Start("C:\\Users\\MainUser\\Documents\\Visual Studio 2010\\Projects\\chatServer\\chatServer\\bin\\Debug\\chatServer.exe");
}
You also need to be much more specific about where in the code the errors/problems occur.
Use the best guess
|
|
|
|
|
I am making android game in unity it is a bout ball hit a wall then reflect to player and the player should press on right button(cube) of 4 button(cubes)->(up,under,right,left) to reflect the ball to wall and if he press on wrong button the ball do not reflect and the player lose chance of 3 chances , and the player have 3 chances if he lose it the game stop
so -i want c# script to make the ball reflect randomly in 4 position(up,under,right,left)
and -other one to fixed if the player press on right button or no
and -other one to make 3 chances and if he lose it the game stop
please help me ,
thanks,
|
|
|
|
|
You would be much better off asking in the Unity forums for this.
|
|
|
|
|
Member 10205416 wrote: i want c# script
I thought you said you wanted to make the application, sound like you want someone to do all your work for you!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi Everyone,
Is there a way to display the suggestions in a list box with a key from textbox?
let say I type in TextBox "ap" then listbox will show
"apple"
"appliances"
"application"
something like that?
Thanks for your help.
|
|
|
|
|
You will have to build your own logic to implement this kind of textbox.
AutoCompleteMode [^] can be used - however, the dropdown still needs to be implemented.
This sample[^] might help you.
|
|
|
|
|
Thanks Abhinav,
I tried that already but I think I should display the suggestion in Listbox to create an awesome effect.
But thank you for the reply.
|
|
|
|
|
Yes you can do this. The events of the TextBox will help you in this case. You need to capture key events, may be KeyDown, KeyUp, or KeyPress help you in that case. In that event, write code for fetching the list which you need to bind with the listbox on the basis of the text entered in the TextBox and then bind it.
Hope it will work
modified 18-Aug-13 18:17pm.
|
|
|
|
|
Thanks SaqibRasheed,
I think this was a great suggestion. I am just wondering if there's a quick solution for that, like you just have to set the property of a list box same with the autoComplete feature of textbox.
Thanks.
|
|
|
|
|
I have worked with VS 2008 and there was no such property like autoComplete for TextBox. May be later versions of Visual Studio are having such property.
|
|
|
|
|
It's probably the case you just never used TextBox's AutoComplete facility, and have forgotten it was there.
AutoComplete facilities, like those in the ComboBox, have been implemented in the TextBox Control from .NET Framework 2.0~4.5, and in the .NET Client Profile from 3.5 SP1 to 4.
Visual Studio 2008, November, 2007, used FrameWork 3.5.
~
“This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
|
|
|
|
|
You can achieve this functionality using only a WinForms ComboBox.
Just set the ComboBox 'AutoComplete property to 'Suggest; and, set the 'AutoCompleteSoure property to 'ListItems. The AutoSuggest feature will work with the ComboBox 'DropDownStyle property set to either 'Simple, or 'DropDown, but not 'DropDownList.
Enter a set of items, using the design-time editor, for example:
aardvarks
axolotls
bears
beavers
bushmasters
chickens
civet cats
coyotes
dingos
eagles
foxes
gorillas
horses
hyenas
Run the application, and watch what's presented in the auto-dropdown when you type the character "b," and then observe what's presented when you enter "be."
Note that you can set the font, color, style, etc. of what your type, what's displayed after your choice, in the text-entry area, but the suggest drop-down items will use a default Windows small-size font.
You can also define a 'CustomSource for your 'Suggest list[^].
~
“This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
|
|
|
|
|
Thanks BillWood
I tried it before but I think I should display the suggestion on a listbox.
Thanks anyway.
|
|
|
|
|
A ListBox does not implement any AutoComplete facilities; it's one of the simpler Controls. It has no "DropDown" behavior built into it.
Of course, you could spend a few weeks building your own UserControl that contained a TextBox (which does support Auto-Complete), and somehow co-ordinate that with which items are displayed in a ListBox, and by the time you have wasted many hours developing that, and dealing with all the possible complications: you will have duplicated a ComboBox with AutoComplete, and that control is going to be very slow in response, compared to using a ComboBox
good luck, Bill
~
“This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
|
|
|
|
|
If I am understanding you goals correctly give this a try.
Create a new usercontrol and place a textbox and listbox on it.
Then add this as the code behind the control
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class UserControl1 : UserControl
{
private DataTable autocompletelist;
public UserControl1()
{
InitializeComponent();
autocompletelist = new DataTable();
autocompletelist.Columns.Add("item", typeof(string));
autocompletelist.DefaultView.Sort = "[item] ASC";
listBox1.DataSource = autocompletelist;
listBox1.DisplayMember = "item";
listBox1.ValueMember = "item";
listBox1.Visible = false;
fillautocomplete();
textBox1.TextChanged += textBox1_TextChanged;
listBox1.DoubleClick += listBox1_DoubleClick;
this.Leave += new System.EventHandler(this.UserControl1_Leave);
}
private void fillautocomplete()
{
autocompletelist.Rows.Add(new object[] { "ape" });
autocompletelist.Rows.Add(new object[] { "apple" });
autocompletelist.Rows.Add(new object[] { "apppliance" });
autocompletelist.Rows.Add(new object[] { "application" });
autocompletelist.Rows.Add(new object[] { "boy" });
autocompletelist.Rows.Add(new object[] { "bat" });
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
autocompletelist.DefaultView.RowFilter = "[item] LIKE '" + textBox1.Text + "*'";
listBox1.Visible = autocompletelist.DefaultView.Count > 0;
}
private void listBox1_DoubleClick(object sender, System.EventArgs e)
{
if (listBox1.SelectedValue != null)
{
textBox1.Text = listBox1.SelectedValue.ToString();
}
listBox1.Visible = false;
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.Focus();
}
public override string Text
{
get {return textBox1.Text;}
set {textBox1.Text = value;}
}
private void UserControl1_Leave(object sender, EventArgs e)
{
listBox1.Visible = false;
}
}
}
|
|
|
|
|