Hotkey with MouseKeyHook not catching event in C# - c#

I'm building a word lookup application that runs in system tray and when you scan a block of a few words and then press a hotkey combination like Shift + C + V for example.
However, the problem is that when I test it on my personal machine, it works fine. But when through Tester's machine, it is not possible to catch the hotkey press event.
I'm using MouseKeyHook's library.
May everyone help you
Here is my code
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4
}
public Main()
{
System.Diagnostics.Process myProcess = System.Diagnostics.Process.GetCurrentProcess();
myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.High;
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
notify.Visible = true;
this.FormBorderStyle = FormBorderStyle.None;
this.Padding = new Padding(borderSize);
this.panel1.BackColor = borderColor;
this.BackColor = borderColor;
if (File.Exists("hotkey.txt") == false)
{
string noidung = "Shift+F";
File.WriteAllText("hotkey.txt", noidung);
}
manage = new ManageDictionary();
conn = ConnectDB.Connect();
ctrl = new ControlData(m_Events, data, txtSearch);
ctrl.SubscribeGlobal();
resetHotKey();
}
public void resetConnection()
{
conn = ConnectDB.Connect();
}
public void resetHotKey()
{
string[] hot;
string key;
this.hotkey_Events = Hook.GlobalEvents();
if (File.Exists("hotkey.txt"))
{
hot = File.ReadAllLines("hotkey.txt");
key = hot[0];
}
else
{
key = "Shift+F";
}
var subhotkey = Combination.FromString(key);
Action action = () => {
string keyword = Clipboard.GetText().Trim();
if (keyword.Equals(""))
return;
try
{
conn.Open();
ArrayList re;
re = manage.findWord(conn, keyword);
if (re.Count == 0)
{
Dictionary a = new Dictionary(0, "Không tìm thấy kết quả", "", "", "", "");
re.Add(a);
Notification noti = new Notification(re, keyword);
Thread.Sleep(1000);
noti.Show();
}
else
{
Notification noti = new Notification(re, keyword);
Thread.Sleep(1000);
noti.Show();
}
}
catch (Exception)
{
MessageBox.Show("Kết nối thất bại");
}
conn.Close();
};
var assignment = new Dictionary<Combination, Action>
{
{subhotkey, action}
};
this.hotkey_Events.OnCombination(assignment);
}

Related

c# and serial port

I'm trying to do an application in c #, which sends a text file through a serial port to a machine.
all good and beautiful if the machine is put in download mode.
if the operator forgets to put the machine on download mode .... here comes the problem, I have a writetimout exception.
I would like to use this exception or anything else to resume the process and my program will try to reload the file into the machine.
below is my code
private void incarca_button_Click(object sender, EventArgs e)
{
string open_folder = cale_txt.Text.Replace(Environment.NewLine, "");
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = open_folder;
if (theDialog.ShowDialog() == DialogResult.OK)
{
var onlyFileName = System.IO.Path.GetFileName(theDialog.FileName);
piesa_lbl.Hide();
piesa_txt.Hide();
SerialPort cnc_com = new SerialPort(com);
cnc_com.BaudRate = Int32.Parse(bit);
parity = parity.ToString();
cnc_com.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
cnc_com.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stop_bit);
cnc_com.DataBits = Int32.Parse(data_bit);
cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
cnc_com.Encoding = Encoding.ASCII;
cnc_com.ReadTimeout = 500;
cnc_com.WriteTimeout = 500;
cnc_com.ReadBufferSize = 1000000;
cnc_com.WriteBufferSize = 1000000;
//cnc_com.DtrEnable = true;
//cnc_com.RtsEnable = true;
try
{
cnc_com.Open();
}
catch (UnauthorizedAccessException) { }
catch (System.IO.IOException) { }
catch (ArgumentException) { }
using (StreamReader sr = new StreamReader(open_folder + #"\" + onlyFileName))
{
while (sr.Peek() >= 0)
{
try
{
cnc_com.WriteLine(sr.ReadLine());
//cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
}
catch(TimeoutException wtout)
{
MessageBox.Show("Masina nu este pregatita\nReincarcati programul");
cnc_com.Close();
cnc_com = null;
}
}
}
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
}
}
I would like this piece of code to be executed only if the file was passed successfully to the machine
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
thank you

How can i check in real time and display to the user if a process is still running or not?

Like monitoring the specific process and if the user was quit the process detect that it's not running any more and display it to the user.
In backgroundWorker1_DoWork I did:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
Stopwatch sw = Stopwatch.StartNew();
PopulateApplications();
sw.Stop();
int msec = 1000 - (int)sw.ElapsedMilliseconds;
if (msec < 1) msec = 1; // Don't consume 100% CPU
System.Threading.Thread.Sleep(msec);
}
}
}
Then the PopulateApplication method:
private void PopulateApplications()
{
this.BeginInvoke(new MethodInvoker(delegate
{
var icon = Icon.ExtractAssociatedIcon(GetProcessInfo(GetProcessIntptr()).ProcessFileName);
Image ima = icon.ToBitmap();
ima = resizeImage(ima, new Size(25, 25));
ima = (Image)(new Bitmap(ima, new Size(25, 25)));
String status = GetProcessInfo(GetProcessIntptr()).ProcessResponding ? "Running" : "Not Responding";
}));
}
And the GetProcessInfo:
public ProcessInfo GetProcessInfo(IntPtr hwnd)
{
uint pid = 0;
GetWindowThreadProcessId(hwnd, out pid);
Process proc = Process.GetProcessById((int)pid);
return new ProcessInfo
{
ProcessFileName = proc.MainModule.FileName.ToString(),
ProcessName = proc.ProcessName,
ProcessTitle = proc.MainWindowTitle,
ProcessResponding = proc.Responding
};
}
public class ProcessInfo
{
public string ProcessName { get; set; }
public string ProcessFileName { get; set; }
public string ProcessTitle { get; set; }
public bool ProcessResponding { get; set; }
}
I have a listBox2 control and I want to display there that if the current process is running show Running if the user was quit the process(application) then show instead Running something like Not running
The problem is that if the user quit the process then in this part:
return new ProcessInfo
{
ProcessFileName = proc.MainModule.FileName.ToString(),
ProcessName = proc.ProcessName,
ProcessTitle = proc.MainWindowTitle,
ProcessResponding = proc.Responding
};
Since the process was quit but this is keep being calling from the backgroundworker dowork populateapplication method it will not get anymore the process info since the process no exist. And it will throw exception that:
the process not found
or in some other cases the program just will stop working without any exception.
I played with the PopulateApplications method the problem is that when i exit the process it take some seconds before the HasExited turn true.
bool isexited = false;
Process[] pname;
private void PopulateApplications()
{
this.BeginInvoke(new MethodInvoker(delegate
{
if (isexited == false)
pname = Process.GetProcessesByName(GetProcessInfo(GetProcessIntptr()).ProcessName);
if (pname[0].HasExited)
{
if (pname[0].Responding)
{
isexited = true;
pname[0].CloseMainWindow();
listBox2.Items.Add("Not Running");
}
else
{
isexited = true;
pname[0].Kill();
listBox2.Items.Add("Not Running");
}
}
else
{
pname = Process.GetProcessesByName(GetProcessInfo(GetProcessIntptr()).ProcessName);
listBox2.Items.Add("Running");
var icon = Icon.ExtractAssociatedIcon(GetProcessInfo(GetProcessIntptr()).ProcessFileName);
Image ima = icon.ToBitmap();
ima = resizeImage(ima, new Size(25, 25));
ima = (Image)(new Bitmap(ima, new Size(25, 25)));
}
}));
}

how to release thread is required in multiple thread?

As title, how to release thread is required in multiple thread ?
Ex : I have 5 thread is waiting. I only want thread position 3 is released
I use autoresetevent/manualresetevent/monitor.wait and monitor.pulse but all release thread follow FIFO
help me !!!
UPDATED:
This is form1:
private BackgroundWorker[] threadArray;
public static ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
private void btn_Start_Scraping_Click(object sender, EventArgs e)
{
threadArray = new BackgroundWorker[listView_Site.Items.Count];
for (var f = 0; f < listView_Site.Items.Count; f++)
{
threadArray[f] = new BackgroundWorker();
threadArray[f].DoWork += new DoWorkEventHandler(BackgroundWorkerFilesDoWork);
threadArray[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerFilesRunWorkerCompleted);
threadArray[f].ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerFilesProgressChanged);
threadArray[f].WorkerReportsProgress = true;
threadArray[f].WorkerSupportsCancellation = true;
threadArray[f].RunWorkerAsync(listView_Site.Items[f].Tag.ToString());
}
}
private void BackgroundWorkerFilesDoWork(object sender, DoWorkEventArgs e)
{
....// all above code is fine
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriCaptchaPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
requestCaptcha.Referer = uriloginPage.AbsoluteUri;
//get response.
responseCaptcha = (HttpWebResponse)requestCaptcha.GetResponse();
Stream imagestream = responseCaptcha.GetResponseStream();
if (imagestream != null)
{
Image image = Image.FromStream(imagestream);
if (Directory.Exists(Application.StartupPath + "\\Captcha") == false)
{
Directory.CreateDirectory(Application.StartupPath + "\\Captcha");
}
switch (responseCaptcha.ContentType)
{
case "image/jpeg":
{
saveLocation += ".jpg";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation,ImageFormat.Jpeg);
break;
}
case "image/gif":
{
saveLocation += ".gif";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Gif);
break;
}
case "image/png":
{
saveLocation += ".png";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Png);
break;
}
}
//show form2 to enter captcha
lock (_lockObj)
{
if (Application.OpenForms.OfType<frmCaptchaQuestion>().Any() == false)
{
DoOnUIThread(delegate()
{
_formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage);
_formCaptchaQuestion.Show();
});
}
else
{
DoOnUIThread(() => _formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage));
}
}
//wait and get captcha from form2 and only run thread is required
//this is my problem <<<<========================================
lock (_lockObj)
{
//_manualResetEvent.WaitOne(30000);
//_manualResetEvent.Reset();
//if (clsValueStatic.CaptchaText != null)
//{
// foreach (var id in clsValueStatic.CaptchaText)
// {
while (!_go)
{
Monitor.Wait(_lockObj);
}
// }
//}
}
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriActionLoginPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
}
Form2:
private void textBoxCaptcha_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBox = sender as TextBoxX;
if (textBox != null)
{
clsValueStatic.CaptchaText = textBox.Text.Trim();
textBox.Parent.Parent.Dispose();
frmScrapingAnalysis._manualResetEvent.Set();
}
}
}
PS : Form1 have 1 button to start multiple backgroundworker and show form2 then all backgroundworker wait to get text captcha of textbox from form2
my way want when user enter text of backgroundworker is shown on form2 then only the backgroundworker is released. All other backgroundworker still wait

textbox and dropdown values inserted should store in database using c# asp.net

I got a tab container which has 4 tabs in it. In one of the tab named ADD TASK I got few fields like
(Task Name: --txtbox
Client Name:--drpdwn
Begin Date:--txtbox wid calendar
Due Date:--txtbox wid calendar
Description:--txtbox
Assign To:--drpdown
Status:--drpdown
% Complete:--drpdown)
and an ADD and CANCEL button in the end.
On running the project and inserting the values to those above mentioned fields i will click the add button and after clicking the button the values should store in my DATABASE. i have table named TASK in my DB already.
Please help me with the back end code.
here is my code
protected void BtnAdd_Click(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
int Flag = 0;
objc.TaskName = Session["TaskName"].ToString();
objc.ClientName = DrpClientName.SelectedItem.Text;
objc.BeginDate = Convert.ToDateTime(TxtBeginDate.Text);
objc.DueDate = Convert.ToDateTime(TxtDueDate.Text);
objc.Description = Session["Description"].ToString();
objc.AssignTo = DrpAssignTo.SelectedItem.Text;
objc.Status = DrpStatus.SelectedItem.Text;
objc.PercentageComplete = Convert.ToInt32(DrpPercentageComplete.Text);
int X = obj.InsertTask(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Data Added Successfully";
Panel2.Visible = false;
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Add Data!!!";
}
}
im using layered architecture and i have this code on my ACCESS file of DAL CLASS
public int InsertTask(MTMSDTO M)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#TaskID", M.TaskID);
objParam.Direction = ParameterDirection.Output;
db.Parameters.Add(new SqlParameter("#TaskName", M.TaskName));
db.Parameters.Add(new SqlParameter("#ClientName", M.ClientName));
db.Parameters.Add(new SqlParameter("#BeginDate", M.BeginDate));
db.Parameters.Add(new SqlParameter("#DueDate", M.DueDate));
db.Parameters.Add(new SqlParameter("#Description", M.Description));
db.Parameters.Add(new SqlParameter("#AssignTo", M.AssignTo));
db.Parameters.Add(new SqlParameter("#Status", M.Status));
db.Parameters.Add(new SqlParameter("#PercentageComplete", M.PercentageComplete));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("InsertTask");
if (retval >= 1)
{
return int.Parse(objParam.Value.ToString());
}
else
{
return -1;
}
}
the code is edited now but im getting error as "object reference not set to an instance of an object. " for the line (objc.TaskName = Session["TaskName"].ToString();) which is in BtnAdd_Cick.
Shouldn't your BtnAdd_Click function be something like this instead? You don't currently seem to be calling the InsertTask() function.
protected void BtnAdd_Click(object sender, EventArgs e) {
MTMSDTO m = new MTMSDTO();
m.TaskName = TxtTaskName.Text;
m.ClientName = DrpClientName.Text;
m.BeginDate = TxtBeginDate.Text;
m.DueDate = TxtDueDate.Text;
m.Description = TxtDescription.Text;
m.AssignTo = DrpAssignTo.Text;
m.Status = DrpStatus.Text;
m.PercentageComplete = DrpPercentageComplete.Text;
InsertTask(m);
}
get all values in back end and pass to this function
public bool InsertRecord(string strTableName, string strColumn_Name, string strValues)
{
SqlConnection OBJCONNECTION;
StringBuilder strbQuery;
SqlCommand cmd;
try
{
OBJCONNECTION= new SqlConnection();
OBJCONNECTION.ConnectionString = ConfigurationManager.ConnectionStrings["Basic_ADO"].ConnectionString;//get connection string from web.config file
OBJCONNECTION=
strbQuery = new StringBuilder();
strbQuery.Append("INSERT INTO ");
strbQuery.Append(strTableName);
strbQuery.Append("(" + strColumn_Name + ")");
//strbQuery.Append(" VALUES");
strbQuery.Append("(" + strValues + ")");
cmd = new SqlCommand(strbQuery.ToString(), OBJCONNECTION);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex) { throw ex; }
finally { strbQuery = null; cmd = null;OBJCONNECTION.close();}
}

Received SMS does not show in C# application

I have a C# application that receives SMSes and displays them.
When I send an SMS without this program and using a GSM modem, the SMS gets saved in the GSM modem. When I start the application and click on "read SMS" it shows me only SMSes that were previously received, and which I have already seen in the GSM modem. A new SMS that I sent recently, is not visible.
The program just shows SMSes that are read from the modem. What should I do to show a received SMS immediately in the program?
Code:
public Receive()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnReadMessage = new System.Windows.Forms.Button();
this.rbMessagePhone = new System.Windows.Forms.RadioButton();
this.rbMessageSIM = new System.Windows.Forms.RadioButton();
this.txtOutput = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// btnReadMessage
//
this.btnReadMessage.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnReadMessage.Location = new System.Drawing.Point(192, 80);
this.btnReadMessage.Name = "btnReadMessage";
this.btnReadMessage.Size = new System.Drawing.Size(112, 24);
this.btnReadMessage.TabIndex = 17;
this.btnReadMessage.Text = "Read All Messages";
this.btnReadMessage.Click += new System.EventHandler(this.btnReadMessage_Click);
//
// rbMessagePhone
//
this.rbMessagePhone.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.rbMessagePhone.Location = new System.Drawing.Point(16, 56);
this.rbMessagePhone.Name = "rbMessagePhone";
this.rbMessagePhone.Size = new System.Drawing.Size(64, 24);
this.rbMessagePhone.TabIndex = 25;
this.rbMessagePhone.Text = "Phone";
//
// rbMessageSIM
//
this.rbMessageSIM.Checked = true;
this.rbMessageSIM.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.rbMessageSIM.Location = new System.Drawing.Point(16, 24);
this.rbMessageSIM.Name = "rbMessageSIM";
this.rbMessageSIM.Size = new System.Drawing.Size(64, 24);
this.rbMessageSIM.TabIndex = 24;
this.rbMessageSIM.TabStop = true;
this.rbMessageSIM.Text = "SIM";
//
// txtOutput
//
this.txtOutput.Location = new System.Drawing.Point(8, 304);
this.txtOutput.Multiline = true;
this.txtOutput.Name = "txtOutput";
this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOutput.Size = new System.Drawing.Size(448, 144);
this.txtOutput.TabIndex = 57;
this.txtOutput.Text = "";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbMessageSIM);
this.groupBox1.Controls.Add(this.rbMessagePhone);
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(176, 96);
this.groupBox1.TabIndex = 58;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Message Storage";
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 120);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(448, 176);
this.dataGrid1.TabIndex = 59;
//
// Receive
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(464, 454);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.btnReadMessage);
this.Name = "Receive";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Read Messages";
this.Load += new System.EventHandler(this.Receive_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void btnReadMessage_Click(object sender, System.EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
string storage = GetMessageStorage();
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.All,storage );
foreach(DecodedShortMessage message in messages)
{
Output(string.Format("Message status = {0}, Location = {1}/{2}",
StatusToString(message.Status), message.Storage, message.Index));
ShowMessage(message.Data);
Output("");
}
Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
Output("");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Cursor.Current = Cursors.Default;
}
private void BindGrid(SmsPdu pdu)
{
DataRow dr=dt.NewRow();
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
dr[0]=data.OriginatingAddress.ToString();
dr[1]=data.SCTimestamp.ToString();
dr[2]=data.UserDataText;
dt.Rows.Add(dr);
dataGrid1.DataSource=dt;
}
private void ShowMessage(SmsPdu pdu)
{
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
Output("SENT/UNSENT MESSAGE");
Output("Recipient: " + data.DestinationAddress);
Output("Message text: " + data.UserDataText);
Output("-------------------------------------------------------------------");
return;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
Output("RECEIVED MESSAGE");
Output("Sender: " + data.OriginatingAddress);
Output("Sent: " + data.SCTimestamp.ToString());
Output("Message text: " + data.UserDataText);
Output("-------------------------------------------------------------------");
BindGrid(pdu);
return;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
Output("STATUS REPORT");
Output("Recipient: " + data.RecipientAddress);
Output("Status: " + data.Status.ToString());
Output("Timestamp: " + data.DischargeTime.ToString());
Output("Message ref: " + data.MessageReference.ToString());
Output("-------------------------------------------------------------------");
return;
}
Output("Unknown message type: " + pdu.GetType().ToString());
}
private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch(status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}
private string GetMessageStorage()
{
string storage = string.Empty;
if (rbMessageSIM.Checked)
storage = PhoneStorageType.Sim;
if (rbMessagePhone.Checked)
storage = PhoneStorageType.Phone;
if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}
private void Output(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback stc = new SetTextCallback(Output);
this.Invoke(stc, new object[] { text });
}
else
{
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
}
}
private void Receive_Load(object sender, System.EventArgs e)
{
dt.Columns.Add("Sender",typeof(string));
dt.Columns.Add("Time",typeof(string));
dt.Columns.Add("Message",typeof(string));
}
private void Output(string text, params object[] args)
{
string msg = string.Format(text, args);
Output(msg);
}
If you are using GSMCOMM class, I think you're missing the
comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
though you have to set the modem to notify you of an incoming message. Look at the samples included in the GSMComm Demo.

Categories

Resources