Tech
Forums
Jobs
Books
Events
Videos
Live
More
Interviews
Certification
Training
Career
Members
News
Blogs
Contribute
An Article
A Blog
A Video
An Ebook
An Interview Question
Register
Login
15
Answers
How can I call Serial Port declare in Main Form from a class
hello leong
13y
5.8k
1
Reply
I can call serial port in main from by clicking the button 1.
[code]
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.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
disconnectBtn.Enabled = true;
connectBtn.Enabled = false;
}
catch
{
MessageBox.Show("Error", "Unable To Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (connectBtn.Enabled == false)
{
textBox1.Text = "Connected";
}
}
private void disconnectBtn_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
connectBtn.Enabled = true;
disconnectBtn.Enabled = false;
}
catch
{
MessageBox.Show("Error", "Unable To Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (disconnectBtn.Enabled == false)
{
textBox1.Text = "Disconnected";
}
}
private void button1_Click_1(object sender, EventArgs e)
{
serialPort1.Write(new byte[] {0x55}, 0, 1); //OK
}
private void button2_Click(object sender, EventArgs e)
{
Class1 sp = new Class1();
sp.serialOut();
}
}
}
[/code]
But, when i click button2 link to class2 to call serial port, it does not work.
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
class Class1
{
public void serialOut()
{
MainForm _mainForm = new MainForm();
_mainForm.serialPort1.Open(); //UnauthorizedAccessException was unhandle
_mainForm.serialPort1.Write(new byte[] { 0x55 }, 0, 1); //InvalidOperationException was unhandle
}
}
}
[/code]
I had set the serialPort1 to public in properties.
How can i solve this? Thank you.
Post
Reset
Cancel
Answers (
15
)
Next Recommended Forum
Abstract Class
Select query without identy column