"System.UnauthorizedAccessException" error when opening second serial port - c#

i Need to open a second serialPort in my Visual C# program to read data from my arduino.
it already worked fine, but in the case you see below it does not work..
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 System.IO.Ports;
using CommandsPD4I;
namespace CSharpExample
{
public partial class CSharpExample : Form
{
public ComMotorCommands motor1;
public CSharpExample()
{
InitializeComponent();
motor1 = new ComMotorCommands();
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
SerialPort arduino;
delegate void InvokeLB(string Data);
InvokeLB lbRecievedDelegate;
int xPos = 0;
private void StartBtn_Click(object sender, EventArgs e)
{
// Set comm settings for motor 1
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
// Set motor address
motor1.MotorAddresse = Convert.ToInt32(Motor1ID.Value);
// Set relative positioning mode
motor1.SetPositionType(1);
// Start travel profile
if (motor1.ErrorFlag)
{
StatusLabel1.Text = "Status 1: " + motor1.ErrorMessageString;
}
else
{
StatusLabel1.Text = "Status 1: OK";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
// Stop travel profile
motor1.StopTravelProfile();
}
private void timer1_Tick(object sender, EventArgs e)
{
lblPosition.Text = Convert.ToString(motor1.GetPosition());
lblStatus.Text = motor1.ErrorMessageString;
// this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
// xPos++;**strong text**
}
private void btnHoch_Click(object sender, EventArgs e)
{
motor1.SetDirection(0);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void btnRunter_Click(object sender, EventArgs e)
{
motor1.SetDirection(1);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void numericSchritte_ValueChanged(object sender, EventArgs e)
{
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
private void numericGeschwindigkeit_ValueChanged(object sender, EventArgs e)
{
motor1.SetMaxFrequency(Convert.ToInt32(numericGeschwindigkeit.Value));
}
private void btnDiagramm_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
timer1.Stop();
}
else
{
timer1.Start();
}
}
private void btnResetDiagramm_Click(object sender, EventArgs e)
{
this.chart1.Series["Kraft"].Points.Clear();
xPos = 0;
}
private void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string RecievedLine = " ";
while (RecievedLine != "")
{
RecievedLine = arduino.ReadLine();
lblKraft.Invoke(lbRecievedDelegate, new object[] { RecievedLine });
}
}
void Invokelabel1(string Data)
{
label1.Text = Data;
this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
xPos++;
}
private void btnArduino_Click(object sender, EventArgs e)
{
//Hier erstellen wir unseren Serialport und legen die Einstellungen fest
arduino = new SerialPort("COM7", 9600);
if (!arduino.IsOpen)
{
arduino.Open();
if (arduino.IsOpen)
{
lblArduino.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(0)))));
lblArduino.Text = "Verbunden mit " + arduino.PortName;
}
}
lbRecievedDelegate = new InvokeLB(Invokelabel1);
arduino.DataReceived += new SerialDataReceivedEventHandler(arduino_DataReceived); //DataRecieved Event abonnieren
}
}
}
When i leave out this:
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
then it works..
I hope you can help :)

Related

How to make two forms receive information from the serial port that receives information from Arduino?

I am developing a graphical interface that reads variables from different sensors that arrive through the serial port, so far I have managed to read all the variables with a single form but now I want to have two forms.
The first form asks the user to choose the COM and confirms whether the connection was successful or not. Once the connection is successful, the second form is opened where the variables from the sensors will be shown in "labels", the readings sent from Arduino are read by the serial port and stored in an array:
data[0], data[1], data[2] etc...
This is the first form where Serialport1 is found and the data arrives through the serialPort1_DataReceived event:
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 System.IO.Ports;
using System.Media;
namespace AUTOCLAVES_GUI
{
public partial class GUI_AUTOCLAVES_GENERADOR_DE_VAPOR : Form
{
/*VARIABLES GLOBALES*/
string puerto_seleccionado;
public GUI_AUTOCLAVES_GENERADOR_DE_VAPOR()
{
InitializeComponent();
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private void Salir_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Minimizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void Maximizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
Maximizar.Visible = false;
Restaurar.Visible = true;
}
private void Restaurar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Restaurar.Visible = false;
Maximizar.Visible = true;
}
private void MenuSideBar_Click(object sender, EventArgs e)
{
if (Sidebar.Width == 270)
{
Sidebar.Visible = false;
Sidebar.Width = 68;
SidebarWrapper.Width = 90;
LineaSidebar.Width = 68;
AnimacionSidebar.Show(Sidebar);
}
else
{
Sidebar.Visible = false;
Sidebar.Width = 270;
SidebarWrapper.Width = 300;
LineaSidebar.Width = 268;
AnimacionSidebarBack.Show(Sidebar);
}
}
private void bunifuFlatButton8_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
serialPort1.Dispose();
serialPort1.Open();
CheckForIllegalCrossThreadCalls = false;
label2.Text = "CONEXIÓN EXITOSA";
label2.ForeColor = Color.Green;
label2.Font = new Font(label2.Font, FontStyle.Bold);
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
catch
{
label2.Text = "CONEXIÓN FALLIDA";
label2.ForeColor = Color.Red;
label2.Font = new Font(label2.Font, FontStyle.Bold);
MessageBox.Show("REVISE CONEXIÓN DE ARDUINO", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
puerto_seleccionado = comboBox1.Text;
serialPort1.PortName = puerto_seleccionado;
}
private void bunifuFlatButton7_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
label2.Text = "SIN CONEXIÓN";
label2.ForeColor = Color.White;
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private Form activeForm = null;
private void openChildForm(Form childForm)
{
if (activeForm != null)
activeForm.Close();
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string[] data = serialPort1.ReadLine().Split(',');
if (data.Length > 10)
{
}
else
{
MessageBox.Show("Intente nuevamente", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
}
Here is my second form:
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 AUTOCLAVES_GUI
{
public partial class MUESTREO_EN_TIEMPO_REAL : Form
{
public MUESTREO_EN_TIEMPO_REAL()
{
InitializeComponent();
}
private void MUESTREO_EN_TIEMPO_REAL_Load(object sender, EventArgs e)
{
}
private void Salir_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope someone can help me overcome this problem.

Bunifu cannot access non-static property Visible

I have been trying to make a menu which has 3 tabs. Login, News and website. I created user control and named it LoginTab.cs now I put the login panels in there LoginTab.cs, NewsTab. Now I am trying to make it visible and invisible depending on what tab people click. So if someone clicks news then the LoginTab goes away and shows the News tab. My problem is that I can't used LoginTab.Visible because its showing me "Cannot access non-static property 'Visible' in static context. How would I do this?
Main.cs
using System;
using System.Windows.Forms;
using UHWID;
namespace AnixLoader
{
public partial class Main : Form
{
bool username;
bool usergroup;
String SimpleUID = UHWIDEngine.SimpleUid;
String AdvancedUID = UHWIDEngine.AdvancedUid;
public Main()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Panel2_Paint(object sender, PaintEventArgs e)
{
}
private void Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void Sdads_Click(object sender, EventArgs e)
{
}
private void PictureBox2_Click(object sender, EventArgs e)
{
}
private void CloseMenu_Click(object sender, EventArgs e)
{
Environment.Exit(0); // Closes Menu
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
LoginTab.Visible = true;
NewsTab.Visible = false;
}
private void News_Click(object sender, EventArgs e)
{
LoginTab.Visible = false;
NewsTab.Visible = true;
}
private void BtnMenu_Click(object sender, EventArgs e)
{
if (sidemenu.Width == 60)
{
//EXPAND
// 1. Expand the panel , w = 300
// 2. Show Logo
sidemenu.Visible = false;
sidemenu.Width = 300;
PanelAnimator.ShowSync(sidemenu);
LogoAnimator.ShowSync(Anix_Logo);
}
else
{
//MINIMIZE
//Using Bunifu Animator
// 1. Hide the logo
// 2. Slide the panel, w = 60
LogoAnimator.Hide(Anix_Logo);
sidemenu.Visible = false;
sidemenu.Width = 60;
PanelAnimator.ShowSync(sidemenu);
}
}
private void MainPanel_Paint(object sender, PaintEventArgs e)
{
}
}
}
LoginTab.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AnixLoader
{
public partial class LoginTab : UserControl
{
public LoginTab()
{
InitializeComponent();
}
private void LoginTab_Load(object sender, EventArgs e)
{
}
private void LoginText_Click(object sender, EventArgs e)
{
}
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
}
private void Login_Click(object sender, EventArgs e)
{
}
private void Password_Click(object sender, EventArgs e)
{
}
}
}
I have resolved the problem by changing from this
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
LoginTab.Visible = true;
NewsTab.Visible = false;
}
private void News_Click(object sender, EventArgs e)
{
LoginTab.Visible = false;
NewsTab.Visible = true;
}
to this
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{ // Log in button
this.MainPanel.Controls.Clear();
this.MainPanel.Controls.Add(new LoginTab());
}
private void News_Click(object sender, EventArgs e)
{ // News button
this.MainPanel.Controls.Clear();
this.MainPanel.Controls.Add(new NewsTab());
}

C# Serial Port Communication Arduino

I have a project where I need to communicate with Arduino over the serial ports. The problem I face is that I cannot print continously the data I receive from the serial monitor on multiple lines on a richtextbox. When I press the button "Reveice" I do receive only one value and after this, pressing again the Receive button will overwrite the line.
I'm tring to fix this for few days, but it's my first time programming in c# so I'm asking for your help.
The code:
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 System.IO.Ports;
namespace aplicatie_comanda_v1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvilablePorts();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button3.Enabled = true;
button1.Enabled = false;
receive.Enabled = false;
richTextBox1.Clear();
}
private void label1_Click(object sender, EventArgs e)
{
}
void getAvilablePorts()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "" && serialPort1 != null && serialPort1.IsOpen)
{
richTextBox1.Text = "Select COM port and BAUD rate !";
serialPort1.Close();
}
else
{
string cmd = Convert.ToString(comboBox1.Text);
int baud = Convert.ToInt32(comboBox2.Text);
serialPort1.PortName = cmd;
serialPort1.BaudRate = baud;
serialPort1.DtrEnable = true;
serialPort1.RtsEnable = true;
serialPort1.Open();
progressBar1.Value = 100;
button1.Enabled = true;
button2.Enabled = true;
textBox1.Enabled = true;
button3.Enabled = false;
}
}
catch (UnauthorizedAccessException)
{
richTextBox1.Text = "Unauthorized !";
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
serialPort1.Write(text);
}
private void receive_Click(object sender, EventArgs e)
{
try
{
richTextBox1.Text = serialPort1.ReadLine() + "\n";
}
catch (TimeoutException)
{
richTextBox1.Text = "Timeout !";
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Write("w");
}
private void button5_Click(object sender, EventArgs e)
{
serialPort1.Write("s");
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
}
private void button6_Click(object sender, EventArgs e)
{
serialPort1.Write("a");
}
private void button7_Click(object sender, EventArgs e)
{
serialPort1.Write("d");
}
private void button12_Click(object sender, EventArgs e)
{
serialPort1.Write("b");
}
private void button13_Click(object sender, EventArgs e)
{
string cmd = Convert.ToString(trackBar1.Value);
serialPort1.Write(cmd);
}
private void button8_Click(object sender, EventArgs e)
{
serialPort1.Write("q");
}
private void button11_Click(object sender, EventArgs e)
{
serialPort1.Write("e");
}
private void button9_Click(object sender, EventArgs e)
{
serialPort1.Write("z");
}
private void button10_Click(object sender, EventArgs e)
{
serialPort1.Write("c");
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
while (serialPort1.IsOpen)
{
try
{
string date = serialPort1.ReadLine();
richTextBox1.Text = date + "\n";
}
catch (TimeoutException)
{
richTextBox1.Text = "Timeout !";
}
}
}
}
}
Print screen of the final app: http://i.imgur.com/5f8EOly.png
Thank you !
I haven't written any Serial applications in C# yet, but already did a few projects involving Java <-> Arduino communication.
My first guess would be that you overwrite the existing line with the received line.
richTextBox1.Text = serialPort1.ReadLine() + "\n";
instead you would want:
richTextBox1.Text += serialPort1.ReadLine() + "\n";
Also you should take a look at this article on MSDN:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx
This shows how you could use Events to continuously receive text from the Arduino.

Backgroundworker lag when starting, split method for multiple threads

The below code is for searching files. The thing is that when I select a large folder (like C disk) program starts with some delay. I think I need to divide disk into smaller parts (folders) and run it on different threads, but I do not know how.
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 System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Collections;
using System.Diagnostics;
namespace failu_paieska
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
FolderBrowserDialog Folder = new FolderBrowserDialog();
Stopwatch stopwatch = new Stopwatch();
static List<string> lstFilesFound = new List<string>();
int fileCount;
int fileCount1;
//string test;
private void Form1_Load(object sender, EventArgs e)
{
//label2.Text = Environment.ProcessorCount.ToString();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = Folder.ShowDialog();
textBox2.Text = Folder.SelectedPath.ToString();
}
private void IdetiIListbox()
{
foreach (string n in lstFilesFound.ToList())
{
stopwatch.Start();
if (Path.GetFileName(n).Contains(textBox1.Text.ToString()))
{
this.BeginInvoke(new MethodInvoker(() =>
{
listBox1.Items.Add(n);
//progressBar1.Value++;
}));
}
}
stopwatch.Stop();
int paieska = listBox1.Items.Count;
this.BeginInvoke(new MethodInvoker(() =>
{
textBox3.Text = Convert.ToString(stopwatch.Elapsed);
}));
}
public void Ieskoti1()
{
foreach (string ff in Directory.EnumerateFiles(textBox2.Text.ToString(), "*.*"))
{// Paima failus is pirmo katalogo
lstFilesFound.Add(ff);
fileCount1 = lstFilesFound.Count();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync(textBox2.Text.ToString());
}
}
static void DirSearch(string sDir)
{
foreach (string d in Directory.EnumerateDirectories(sDir))
{
try
{
lstFilesFound.Add(d);
//visoFailu += 1;
foreach (string f in Directory.EnumerateFiles(d, "*.*"))
{
//visoFailu += 1;
lstFilesFound.Add(f);
}
DirSearch(d);
}
catch (Exception ee)
{
}
continue;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label4.Text = (e.ProgressPercentage.ToString() + "%");
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//DirSearch(textBox2.Text.ToString());
Ieskoti1();
DirSearch(textBox2.Text.ToString());
// IdetiIListbox();
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
}
}
private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
{
//DirSearch(textBox2.Text.ToString());
IdetiIListbox();
if (e.Cancelled == true)
{
MessageBox.Show("Cancelled!");
}
else if (e.Error != null)
{
MessageBox.Show("Error: " + e.Error.Message);
}
else
{
MessageBox.Show("Done!");
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
fileCount = Directory.GetFiles(textBox2.Text.ToString()).Length;
}
}
}

Problem with appendText in c#

I have an app that has 3 text boxes, (users name, what company they are from, and who they are visiting) A button to print, and a keyboard on the screen (monitor is touch screen). I have everything working and functioning...
BUT, the one thing that does not work is when the user points to previous character in the text box that has already been typed, the buttons that "AppendText" (keyboard) do not start typing where the user pointed but it continues typing at the end of what has been typed.
Is this because of "AppendText" or some other issue that I have in my code?
I also am trying to get the first text box (Name_Box) to be sent to form one, which then will be split into two labels (1, first name| 2, last name) right now I have it being sent to one label But I want to split it so the first name is stacked above the second name in the next form (which is printed out).
Thank you so much.
Here is my code: First Form
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
namespace SMART
{
public partial class Form1 : Form
{
private TextBox tbSelected; // Last focused TextBox
private int posCaret; // Caret position
private int selLength; // Selection length
public Form1()
{
InitializeComponent();
// We will use leave event for textboxes
Name_Box.Leave += new System.EventHandler(textBox_Leave);
Company_Box.Leave += new System.EventHandler(textBox_Leave);
Visiting_Box.Leave += new System.EventHandler(textBox_Leave);
// Set initial selection to the first textbox
Name_Box.Select();
tbSelected = Name_Box;
posCaret = 0;
selLength = 0;
}
// Leave event handler
private void textBox_Leave(object sender, EventArgs e)
{
// Remember the last focused thextbox,
// the caret position in it and the selection length
tbSelected = (TextBox)sender;
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
// Helper method to restore selection
private void RestoreLastSelection()
{
tbSelected.Select();
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
private void Form1_Load(object sender, EventArgs e)
{
label5.Text = DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
label5.Text = DateTime.Now.ToString();
Form2 frm = new Form2(Name_Box.Text);
frm.Show();
frm.Close();
StreamWriter sw;
sw = File.AppendText ("C:\\SignIn.txt");
sw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + " | Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");
sw.Close ();
Name_Box.Clear();
Company_Box.Clear();
Visiting_Box.Clear();
}
private void button42_Click(object sender, EventArgs e)
{
//SPACE BAR
tbSelected.AppendText(" ");
}
private void button24_Click(object sender, EventArgs e)
{
//DELETE
string t = tbSelected.Text;
if (t.Length > 0)
{
tbSelected.Text = t.Remove(t.Length - 1);
}
}
private void button12_Click(object sender, EventArgs e)
{
tbSelected.AppendText("-");
}
private void button13_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Q");
}
private void button14_Click(object sender, EventArgs e)
{
tbSelected.AppendText("W");
}
private void button15_Click(object sender, EventArgs e)
{
tbSelected.AppendText("E");
}
private void button16_Click(object sender, EventArgs e)
{
tbSelected.AppendText("R");
}
private void button17_Click(object sender, EventArgs e)
{
tbSelected.AppendText("T");
}
private void button18_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Y");
}
private void button19_Click(object sender, EventArgs e)
{
tbSelected.AppendText("U");
}
private void button20_Click(object sender, EventArgs e)
{
tbSelected.AppendText("I");
}
private void button21_Click(object sender, EventArgs e)
{
tbSelected.AppendText("O");
}
private void button22_Click(object sender, EventArgs e)
{
tbSelected.AppendText("P");
}
private void button25_Click(object sender, EventArgs e)
{
tbSelected.AppendText("A");
}
private void button26_Click(object sender, EventArgs e)
{
tbSelected.AppendText("S");
}
private void button27_Click(object sender, EventArgs e)
{
tbSelected.AppendText("D");
}
private void button28_Click(object sender, EventArgs e)
{
tbSelected.AppendText("F");
}
private void button29_Click(object sender, EventArgs e)
{
tbSelected.AppendText("G");
}
private void button30_Click(object sender, EventArgs e)
{
tbSelected.AppendText("H");
}
private void button31_Click(object sender, EventArgs e)
{
tbSelected.AppendText("J");
}
private void button32_Click(object sender, EventArgs e)
{
tbSelected.AppendText("K");
}
private void button33_Click(object sender, EventArgs e)
{
tbSelected.AppendText("L");
}
private void button35_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Z");
}
private void button36_Click(object sender, EventArgs e)
{
tbSelected.AppendText("X");
}
private void button37_Click(object sender, EventArgs e)
{
tbSelected.AppendText("C");
}
private void button38_Click(object sender, EventArgs e)
{
tbSelected.AppendText("V");
}
private void button39_Click(object sender, EventArgs e)
{
tbSelected.AppendText("B");
}
private void button40_Click(object sender, EventArgs e)
{
tbSelected.AppendText("N");
}
private void button41_Click(object sender, EventArgs e)
{
tbSelected.AppendText("M");
}
private void button2_Click_1(object sender, EventArgs e)
{
tbSelected.AppendText("'");
}
private void button3_Click(object sender, EventArgs e)
{
tbSelected.Clear();
}
}
}
Heres is my code: Second Form
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.Drawing.Printing;
namespace SMART
{
public partial class Form2 : Form
{
public Form2(string strTextBox)
{
InitializeComponent();
label3.Text = strTextBox;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString();
PrintDocument pd = new PrintDocument();
Margins margins = new Margins(0, 0, 0, 0);
pd.DefaultPageSettings.Margins = margins;
pd.PrintPage += new PrintPageEventHandler(PrintImage);
pd.Print();
/*
//My sad attempt at splitting the Name
var fullname = strTextBox;
var names = fullname.Split (" ");
label3.Text = names[0];
label5.Text = names[1];
*/
}
void PrintImage(object o, PrintPageEventArgs e)
{
int x = SystemInformation.WorkingArea.X;
int y = SystemInformation.WorkingArea.Y;
int width = this.Width;
int height = this.Height;
Rectangle bounds = new Rectangle(x, y, width, height);
Bitmap img = new Bitmap(width, height);
this.DrawToBitmap(img, bounds);
Point p = new Point(0, 0);
e.Graphics.DrawImage(img, p);
}
}
}
You're right in that your problem is the use of AppendText, which always appends to the end (that's what append means).
You need to Insert the character at the current carat position.
You might do better to post a message that simulates a keypress from a physical keyboard.
If you want to insert text at the user's current position, you can use SelectedText. This will replace the current selection (if the user has selected characters):
tbSelected.SelectedText = "V";
Edit: The problem is in here:
private void button24_Click(object sender, EventArgs e)
{
//DELETE
string t = tbSelected.Text;
if (t.Length > 0)
{
tbSelected.Text = t.Remove(t.Length - 1);
}
}
You set the text, which returns the cursor to the beginning of the textbox. You should set tbSelected.SelectionStart after you clear the text.

Categories

Resources