I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
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;
namespace AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}
Related
I am having a problem with my code where i run into an error when i try to click the join button. It says the ap.Connect(authrequest) is returning a null value so it cannot return a bool value. I am doing this in visual studio in a .net forms i think.
Thanks for you help.
Ps i am a student
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 SimpleWifi;
namespace desk_flat
{
public partial class formConnect : Form
{
private static Wifi wifi;
public formConnect()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wifi = new Wifi();
List<AccessPoint> aps = wifi.GetAccessPoints();
foreach (AccessPoint ap in aps)
{
ListViewItem listobj = new ListViewItem(ap.Name);
listobj.SubItems.Add(ap.SignalStrength + "'''");
listobj.Tag = ap;
lstWifi.Items.Add(listobj);
}
}
private bool ConnectWifi(AccessPoint ap, string password)
{
AuthRequest authrequest = new AuthRequest(ap);
authrequest.Password = password;
return ap.Connect(authrequest);
}
private void btnJoin_Click(object sender, EventArgs e)
{
if (lstWifi.Items.Count > 0 && txtbPassword.Text.Length > 0)
{
ListViewItem selectedItem = lstWifi.SelectedItems[0];
AccessPoint ap = (AccessPoint)selectedItem.Tag;
if (ConnectWifi(ap, txtbPassword.Text))
{
lblStatus.Text = "You have connected to " + ap.Name;
}
else
{
lblStatus.Text = "Connection has failed";
}
}
else
{
lblStatus.Text = "Enter a password or select a network";
}
}
}
}
I'm new here, and also new in C# programming in Visual Studio.
Currently I have an assignment about C# refactoring.
This is the original class
calculator.cs
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;
namespace HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
public calculator()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void calorieCalculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = (66
+ (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
}
else
{
txtCalories.Text = (655
+ (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
}
}
private void weightCalculation()
{
double maleVariable = 50;
double femaleVariable = 45.5;
double Formula = (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12) + Convert.ToDouble(txtInches.Text)));
if (rbtnMale.Checked)
{
txtIdealWeight.Text = ((maleVariable + Formula) * 2.2046).ToString();
}
else
{
txtIdealWeight.Text = ((femaleVariable + Formula) * 2.2046).ToString();
}
}
private void txtFeetValidation()
{
double feet;
if (!double.TryParse(txtFeet.Text, out feet))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
}
}
private void txtInchesValidation()
{
double inches;
if (!double.TryParse(txtInches.Text, out inches))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
}
private void txtWeightValidation()
{
double weight;
if (!double.TryParse(txtWeight.Text, out weight))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
}
private void txtAgeValication()
{
double age;
if (!double.TryParse(txtAge.Text, out age))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtFeetValidation();
txtInchesValidation();
txtWeightValidation();
txtAgeValication();
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
calorieCalculation();
weightCalculation();
}
private void label8_Click(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAddPatient_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtIdealWeight.Text))
{
Form secondForm = new patientInfo(this);
secondForm.Show();
}
else
{
MessageBox.Show("Please enter all datas and click on 'Add Patient' to add patient's records");
}
}
private void btnPatientList_Click(object sender, EventArgs e)
{
Form secondForm = new patientList(this);
secondForm.Show();
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
The following classed are the parent class and sub-classes I would like to setup.
parent: calculator.cs
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;
namespace HUANG_Kai_30077528_Assign1
{
public partial class calculator : Form
{
//private string maleCaloriesCalculation();
//private string maleWeightCalculation();
//private string femaleCaloriesCalculation();
//private string femaleWeightCalculation();
public calculator()
{
InitializeComponent();
}
private void rbtnMale_CheckedChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//Clear old results
txtIdealWeight.Text = "";
txtCalories.Text = "";
/* Validate User Input: */
//Validate height (feet) is numeric value
double result;
if (!double.TryParse(txtFeet.Text, out result))
{
MessageBox.Show("Feet must be a numeric value.");
txtFeet.Select();
return;
}
//Validate height (inches) is numeric value
if (!double.TryParse(txtInches.Text, out result))
{
MessageBox.Show("Inches must be a numeric value.");
txtInches.Select();
return;
}
//Validate weight is numeric value
if (!double.TryParse(txtWeight.Text, out result))
{
MessageBox.Show("Weight must be a numeric value.");
txtWeight.Select();
return;
}
//Validate age is numeric value
if (!double.TryParse(txtAge.Text, out result))
{
MessageBox.Show("Age must be a numeric value.");
txtAge.Select();
return;
}
if (!(Convert.ToDouble(txtFeet.Text) >= 5))
{
MessageBox.Show("Height has to be equal to or greater than 5 feet!");
txtFeet.Select();
return;
}
/*End validation*/
calculation();
}
private void calculation()
{
if (rbtnMale.Checked)
{
txtCalories.Text = maleCalculator.maleCalories().ToString();
//txtCalories.Text = maleCalculator.maleCaloriesCalculation();
//txtIdealWeight.Text = maleCalculator.maleWeightCalculation();
}
else
{
txtCalories.Text = femaleCalculator.femaleCaloriesCalculation();
txtIdealWeight.Text = femaleCalculator.femaleWeightCalculation();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
rbtnMale.Checked = false;
rbtnFemale.Checked = false;
txtFeet.Text = "";
txtInches.Text = "";
txtWeight.Text = "";
txtAge.Text = "";
txtCalories.Text = "";
txtIdealWeight.Text = "";
}
}
}
subclass: maleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class maleCalculator: calculator
{
//private string maleCaloriesCalculation;
//private string maleWeightCalculation;
public maleCalculator maleCalories()
{
(66 + (6.3 * Convert.ToDouble(txtWeight.Text))
+ (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
return maleCalories();
//this.txtCalories.Text = new maleCalculator.maleCalories;
}
public maleCalculator maleWeight()
{
((50 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return maleWeight();
}
}
}
subclass: femaleCalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HUANG_Kai_30077528_Assign1
{
class femaleCalculator : calculator
{
public double femaleCaloriesCalculation()
{
txtCalories.Text = (655 + (4.3 * Convert.ToDouble(txtWeight.Text))
+ (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
+ Convert.ToDouble(txtInches.Text)))
- (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
return femaleCaloriesCalculation();
}
public double femaleWeightCalculation()
{
txtIdealWeight.Text = ((45.5 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
+ Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();
return femaleWeightCalculation();
}
}
}
As we can see, these two sub-classes are use to do the calculation for the calories and ideal weight. They are plan to take place of private void calorieCalculation() and private void weightCalculation() in the original class calculator.cs.
The function I need is like this:
When I execute the program and need to calculate the idealWeight and calories, the parent class calculator.cs will get the result from the formula contain in the sub-class, and ToString in the text box. That's why there are txtCalories and txtIdealWeight inside the calculator.cs.
So the question is how to get the results in the sub-class, and fill in the text boxes?
Guys, please help me with it as this is really important to me!!
Thank you all!!
Do you mean a virtual function? If so,
class Ancestor
{
public virtual int DoSomething()
{
// execute commands here.
// for now just throw exception.
throw new NotImplementedException();
}
}
class Derived_A : Ancestor
{
public override int DoSomething()
{
return 1 + 1;
}
}
class Derived_B : Ancestor
{
public override int DoSomething()
{
return 1 + 2;
}
}
This is ancestry, with virtual functions. For more on this:
Practical usage of virtual functions in c#
http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx
This type of code can also be done with interfaces. See http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx.
Hi am a fairly novice when it comes to c# and I have being trying to read out a text file then splitting it into sections with classes but have trouble with where to declare them an then how to cycle through the records. here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace Assignment_3
{
public partial class Form1 : Form
{
string s;
string ss;
int i = 1;
string infilename;
int num;
SortedList sList = new SortedList();
int x = 0;
public Form1()
{
InitializeComponent();
student myself = new student();
infilename = "text.txt";
StreamReader sr1 = new StreamReader(infilename);
sList.Clear();
while ((s = sr1.ReadLine()) != null)
{
string[] strs = s.Split(',');
myself.firstname = strs[0];
myself.middlename = strs[1];
myself.surname = strs[2];
myself.dob = DateTime.Parse(strs[3]);
myself.dob.ToString(strs[3]);
myself.sex = strs[4];
ss = myself.dob.ToString("u");
sList.Add(myself.firstname, myself);
}
sr1.Close();
num = sList.Count;
student[] pArray = new student[num];
string[] keys = new string[num];
foreach (DictionaryEntry d in sList)
{
keys[x] = (string)d.Key;
pArray[x] = (student)d.Value;
x++;
}
if (i == 0)
{lblmessage.Text = "Already at the first record."; i = 1; }
if (i == num)
{lblmessage.Text = "Already at the last record.";i = num-1; }
lbllastname.Text = pArray[i].surname;
lblfirstname.Text = pArray[i].firstname;
lblsecondname.Text = pArray[i].middlename;
lbldob.Text = pArray[i].dob.ToString();
lblsex.Text = pArray[i].sex;
}
private void btnlast_Click(object sender, EventArgs e)
{
i = num;
}
private void btnfirst_Click(object sender, EventArgs e)
{
i = 0;
}
private void btnnext_Click(object sender, EventArgs e)
{
i++;
}
private void btnprev_Click(object sender, EventArgs e)
{
i--;
}
}
}
and my class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_3
{
class student
{
public string firstname;
public string middlename;
public string surname;
public DateTime dob;
public string sex;
}
}
anyone have any ideas where am going wrong?? I have no errors but find that the text fields do not update with the new record's and then when stepped through the array class holds the correct amount of records and fields, I feel its going to be something very obvious put cant put my finger on it.
Any help would be very appreciated.
You should create new instance of student inside for loop. Because at the moment you have only one instance of student class and all items in SortedList are pointing to same object.
I am trying to get my Chat system to work. I have a Client/Server launch per an app. I have Client1 talking to Server 2 and Client2 to Server1 but I cannot figure out how to print the information being sent to the servers to the chat windows of their corresponding Clients.
ChatRoom
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
namespace ChatRoom
{
public class Class1:MarshalByRefObject
{
// initialize Arraylist to store users signed into chat room
private static ArrayList userNames = new ArrayList();
private static string chatWindow; // fuck u, now ye be a static var
public void sendMessage(string message)
{
Console.WriteLine(message);
//if (message != null)
// {
//add to chat window
chatWindow += message + Environment.NewLine;
//}
}
//public void test()
//{
// Console.WriteLine("pizza");
//}
public void addUserName(string UserName)
{
String test = UserName;
Console.WriteLine(test);
userNames.Add(test);
Console.WriteLine("0");
}
public void deleteUserName(string userName)
{
if (userName != null)
{
userNames.Remove(userName);
}
}
public ArrayList userList()
{
return userNames; // userNames
}
public string OutputWindow()
{
return chatWindow;
}
}
}
SERVER
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.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using ChatRoom;
using System.Runtime.Remoting.Channels.Http;
using RemoteServer;
namespace RemoteServer
{
public partial class Form1 : Form
{
private int channelNum;
private static string temp;
public Form1()
{
InitializeComponent();
}
private void buttonConfirm_Click(object sender, EventArgs e)
{
temp = textBoxPort.Text;
channelNum = Convert.ToInt32(temp);
HttpChannel ServerChannel = new HttpChannel(channelNum);
Console.WriteLine("httpChannel Set");
this.Close(); // close GUI
ChannelServices.RegisterChannel(ServerChannel, false);
Console.WriteLine("channel registered");
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Class1), "ChatRoom",
WellKnownObjectMode.SingleCall);
Console.WriteLine("working");
Console.WriteLine("Port number is " + channelNum);
Console.ReadKey();
}
}
}
CLIENT
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 ChatRoom;
using RemoteServer;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Threading;
using System.Diagnostics;
using System.Timers;
namespace ClientServerGui
{
public partial class Form1 : Form
{
private Class1 server;
private Thread thread;
//private Thread thread2;
//private HttpChannel ClientHttpChannel;
private string UserName;
public Form1()
{
InitializeComponent();
}
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void ConfigureServer(string port)
{
HttpClientChannel ClientChannel = new HttpClientChannel();
ChannelServices.RegisterChannel(ClientChannel, false);
RemotingConfiguration.RegisterWellKnownClientType(typeof(Class1), "http://localhost:"
+ textBoxPort.Text + "/ChatRoom");
}
private void buttonSend_Click(object sender, EventArgs e)
{
//ArrayList displayUsers = server.userList();
//string send = textBoxSend.Text;
//textBoxChatWindowDisplay.Text += send;
//combine User's name with input text
string send = UserName + ": " + textBoxSend.Text;
while( textBoxSend.Text != "")
{
//send message
server.sendMessage(send);
//Clear and focus to start new message
textBoxSend.Clear();
buttonSend.Focus();
}
textBoxChatWindowDisplay.Text += send;
textBoxChatWindowDisplay.Text = server.OutputWindow();
//textBoxChatWindowDisplay.Text += "\n";
//listBoxUserList.Items.Clear();
// foreach (string x in displayUsers)
// {
// listBoxUserList.Items.Add(displayUsers);
// }
}
public void chatReloadTimer_Tick(object sender, EventArgs e)
{
textBoxChatWindowDisplay.Text = server.OutputWindow();
StartServer();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
//RemoteServer.Form1 port = new RemoteServer.Form1();
//string Serverport = port.ServerPort();
if (textBoxUserName.Text != "")
{
UserName = textBoxUserName.Text;
//ClientHttpChannel = new HttpChannel();
//ChannelServices.RegisterChannel(ClientHttpChannel, false);
if (textBoxPort.Text == "")
{
textBoxPort.Text = "9000";
}
//server1
ConfigureServer(textBoxPort.Text);
//server2
// ConfigureServer(Serverport);
server = new Class1();
//add user
server.addUserName(UserName);
//server.test();
//new thread
thread = new Thread(new ThreadStart(StartServer));
//start thread
thread.Start();
//new thread
//thread2 = new Thread(new ThreadStart(StartServer2));
//start thread
//thread2.Start();
buttonSend.Focus();
System.Windows.Forms.Timer chatReloadTimer = new System.Windows.Forms.Timer();
chatReloadTimer.Interval = (100); // .1 seconds refresh
chatReloadTimer.Tick += new EventHandler(chatReloadTimer_Tick);
chatReloadTimer.Start();
}
}
private void StartServer()
{
string currentChatWindow;
//set array list to capture people joining server
ArrayList usersArrayList = server.userList();
//** BAD FOR CHATROOM STYLE****
//if (listBoxUserList.ItemHeight > 0)//if not enmpy kill all
//{
// //empty listbox
this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Clear(); }));
//}
// Add all users to listbox
//while (usersAL != null)
//{
foreach (string x in usersArrayList)
{
//listBoxUserList.Items.Add(UserName);
this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Add(x); }));
}
//}
//display data to user
currentChatWindow = server.OutputWindow();
//textBoxChatWindowDisplay.Text = currentChatWindow;
this.Invoke(new MethodInvoker(delegate() { textBoxChatWindowDisplay.Text = currentChatWindow; }));
//listBoxUserList.Items.Add(
}
private void Form1_Load(object sender, EventArgs e)
{
//Boolean on = true;
Process start = new Process();
start.StartInfo.FileName = "RemoteServer";
start.Start();
MessageBox.Show("Continue?", "Continue", MessageBoxButtons.OKCancel);
//while (on == true)
//{
// Thread.Sleep(1);
// textBoxChatWindowDisplay.Text = server.OutputWindow();
//}
buttonSend.Focus();
}
}
}
Im trying to emulate the console in a windows forms applicaton. I have made it possible by using two extra threads and a delegate to be able to interact with my multiline textbox.
This somehow seems like I complicate things to much. So my questions.
Is there a better way of doing this?
When i press enter the command does not get sent, first if i press again it get sent? WHy is that? I ahve treid to debug it but failed to find the solution.
EDIT! Im using CsharpSSH, to do the SSH connection. Also I have included my full code now!
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 Tamir.SharpSsh;
using System.IO;
using System.Threading;
using System.Timers;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public string mHost;
SshShell mShell;
public string mInput;
string pattern = "";
bool mInputHolder = false;
string mPattern = "";
int mValue = 0;
bool mStatus = false;
private Thread thrdtwo = null;
private Thread thrdone = null;
public string mKorv;
string mString = "";
delegate void SetTextCallback(string text);
bool clientopen = true;
public Form1()
{
InitializeComponent();
txthost.Text = "sdf.org";
txtuser.Text = "kalle82";
txtpass.Text = "kattsand";
string pattern = "sdf:";
mPattern = pattern;
}
public void button1_Click(object sender, EventArgs e)
{
mShell = new SshShell(Host, User);
mShell.Password = Pass;
//WRITING USER MESSAGE
txtOutput.AppendText("Connecting...");
mShell.Connect();
txtOutput.AppendText("OK");
mShell.ExpectPattern = mPattern;
mShell.RemoveTerminalEmulationCharacters = true;
this.SetText(mShell.Expect(pattern));
txtInput.Focus();
thrdone = new Thread(new ThreadStart(appengine));
thrdone.Start();
}
private void appengine()
{
this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(checkforenter);
// MessageBox.Show("Appengine started");
while (mShell.ShellOpened)
{
thrdtwo = new Thread(new ThreadStart(startthread2));
thrdtwo.Start();
thrdtwo.Join();
// this.SetText(mShell.Expect(pattern));
if (clientopen == false) break;
}
// MessageBox.Show("Appengine stopped");
}
private void startthread2()
{
//Wait for answer
while (mStatus == false)
{
}
}
//Recieves keypressevent
public void checkforenter(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
mStatus = true;
mString = txtInput.Text;
mShell.WriteLine(mString);
this.SetText(mShell.Expect(pattern));
txtOutput.AppendText(txtInput.Text + "\n");
}
mStatus = false;
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtOutput.Text = text.ToString();
}
}
public int checkfortrue()
{
if (mInputHolder != true)
{
mValue = 0;
}
if (mInputHolder == false)
{
mValue = -1;
}
return mValue;
}
public string userInput()
{
while (mInputHolder == true)
{
}
mInputHolder = true;
return txtInput.Text;
}
//Properties
public string Host
{
get
{
return txthost.Text;
}
set
{
txthost.Text = value;
}
}
public string User
{
get
{
return txtuser.Text;
}
set
{
txtuser.Text = value;
}
}
public string Pass
{
get
{
return txtpass.Text;
}
set
{
txtpass.Text = value;
}
}
public string Pattern
{
get
{
return pattern;
}
set
{
pattern = value;
}
}
private void button2_Click(object sender, EventArgs e)
{
clientopen = false;
}
}
}