Not sure if i will be able to formulate my question quite clear but let me try:
So i've written a small piece of code which will give the user the option to select a desired status for his Office Communicator when his PC get locked ( by default it goes automatically on status "away" ) .So here it is the Windows Form wich is basically a combobox and a button .The Combo has four option "Away" , "Busy" , Do not Disturb" and "Online" respectively. All seems fine and the program compiles ok.The Menu appears , you select the status you wish , push the button and then lock your PC - so far all goes perfect.Your Status is as selected .And now comes the Problem.You unlock your PC and try to select a different status , same actions , but when you lock the PC it still shows the previously selected status here is the Button_Click method
public void Btn_Click(Object sender, EventArgs e)
{
// When the button is clicked,
// change the button text, and disable it.
if (Comb.Text == "Away")
{
MessageBox.Show("Saved ! \nYour Status will be 'Away' ");
Method2();
}
else if (Comb.Text == "Busy")
{
MessageBox.Show("Saved ! \nYour Status will be 'Busy' ");
Method1();
}
else if (Comb.Text == "Do Not Disturb")
{
MessageBox.Show("Saved ! \nYour Status will be 'Do Not Disturb' ");
Method3();
}
else
{
MessageBox.Show("Saved ! \nYour Status will be 'Online' ");
Method4();
}
But.Enabled = true;
// Display the greeting label text.
}
So the 4 methods ( Method1 () , 2 ... etc ) are the one to change the status depending on the text in the combo box drop down menu ( the status you select )i have tested all methods separately from each other and they work beautiful thereforfe i exclude a problems with them , is it some logical error ?
Nikolay, give SharpDevelop's debugger a try. In your code's margin click once next to the line if (Comb.Text == "Away") and then hover over the variable names to see what they are set to each time it runs. You can use the "Step over" "Step into" and "Step out" functions to "Execute the highlighted method without looking at the internals", "Debug the Internals of a method" or "Run the current method to the end and then show the next level up" respectively.
If you do this you'll figure out why you're getting an error and it will be MUCH easier to determine where the error is coming from. (For instance, if a variable is set to an unexpected value you'll know to figure out when that changed).
static void SystemEvents_SessionSwitch1(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
System.Threading.Thread.Sleep(500);
CommunicatorAPI.MessengerClass comm = new CommunicatorAPI.MessengerClass();
if (comm.MyStatus==MISTATUS.MISTATUS_AWAY)
{
SetMyPresence1 ();
} else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
ChangeStatus1 ();
}
}
}
Related
I am very new to the programming world and recently dove into c#. I don't want to waste your time so I'll get right to it. I wanted to create a program just to test my knowledge, and thought I could attempt to execute specific blocks of code based on which key on the keyboard is pressed by the user. I tried doing this by creating an event handler that contained if statements, but then realized I didn't know how to have the event handler active in the program.
For example, and as you can see in the below snippet, after the WriteLine in Line 5 lets say I wanted to raise the EventKeyPress event so that it waits for user input and reads the key they have pressed and reacts accordingly, how would I do that?
Again, I'm almost a complete beginner and have searched around for explanations about event handlers for hours and still can't wrap my head around what I am supposed to do or if I am even using the event handler correctly. Thanks in advance!
static void Main();
{
if (search == "Ball")
{
Console.WriteLine("Press enter to exit or backspace to return to the search bar")
// RIGHT HERE
}
else
{
Console.WriteLine("Sorry, I don't recognize {0}", search);
}
void EventKeyPress(object sender, KeyPressEventArgs e)
{
for (int i = 0; i < 1;)
{
if (e.KeyChar == (char)Keys.Enter)
{
// exit app
}
else if (e.KeyChar == (char)Keys.Back)
{
// go back to search
}
else
{
i = 0; // error
}
}
}
}
So, you're asking for something that involves Threading which is not a beginner thing to accomplish at all. The best way to do this for a beginner is to ask for a prompt, then accept as an input. For example.
Console.WriteLine("Hello, what's your name?");
string nameStr = Console.ReadLine();
Console.WriteLine($"Hello, {nameStr}");
You can then use your variable and apply it to an if/while or whatever kind of conditional.
if (nameStr == "Matt"){
//Do This Code.
}
Once you have that code, add a sequential method that will ask the user to return to the main menu or whatever you want it to do.
Main.ReturnMenu(); //Or whatever you want to use.
I am making a simple hangman style game in a C# form. I have it set as textBox1_TextChanged. Except everytime the user backspaces their guess letter it takes in blank space. How can I make it so after the message saying right/wrong it clears the space. I am getting annoyed at it telling the user they made a wrong guess after they backspace. This is my first post on this forum so sorry if the code text is weird. I just want the program to clear the text in the textBox after they guess.
UPDATE: Added suggested information. Now it does everything it is supposed to do. Except it pops up a windows saying " was found in the target word". This happens if guessLetter == null || guessLetter == correct || guessLetter == false.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string guessLetter = textBox1.Text;
//textBox1.ReadOnly = true;
if (targetWord == null)
{
MessageBox.Show("Please start a new game.");
textBox1.Text = ("");
}
else
{
if (targetWord.Contains(guessLetter))
{
MessageBox.Show(guessLetter + " was found in the word");
}
else
{
MessageBox.Show(guessLetter + " was not found in the word");
incorrectGuessCtr++;
textBox3.Text = incorrectGuessCtr.ToString();
}
textBox1.Text = ("");
}
}
Don't only check if the targetWord is null, but also the guessLetter. You'd better use string.IsNullOrEmpty too, since it also checks if the string is empty:
if (!string.IsNullOrEmpty(targetWord) && !string.IsNullOrEmpty(guessLetter))
{
...
}
I guess you should also check if there is exactly one letter entered. That would mean this additional check:
if (guessLetter.Length == 1)
{
...
}
You will enter this event when you write code that changes Text property in textbox. I mean this.
textBox3.Text = incorrectGuessCtr.ToString();
Put something in function arguments or set some flags so that you can identify whether the event is called from user input or your clearing the text.
Just check how many times this function is called when user press backspace. You will get the idea.
Background:
A WinForms app, originally written in .NET 1.1 migrated via Visual
Studio to .NET 4.0. Typical menu bar at the top of main app form (NB:
not migrated to ToolStripMenuItem), as you might expect there is a
File menuitem that contains an Exit menu item.
I have implemented Ctrl-L shortcut which will bring up a modal lock
form. I also have a timer component on the main form which will
automatically bring up the lock form if there's no activity for
configurable amount of time.
When the lock form is shown you can either unlock (requiring user to
login again) or quit. If you choose to quit then my code does a
fileExitMenuItem.PerformClick() call.
Problem:
For some strange reason after the migration if I quit from the lock
form which was displayed either automatically or due to Ctrl-L
shortcut then I get a NullReferenceException thrown on the
fileExitMenuItem.PerformClick() line of code.
fileExitMenuItem is not null; with break-when-exception-thrown
switched on I can browse all of fileExitMenuItems properties.
I can break in the designer code of the form and watch the click event
handler being attached. If I use the File >> Exit menu item directly I
can break on the code in the event handler.
So this is a total WTF moment. Any suggestions on what to look at will be greatly appreciated
[UPDATE 1] As requested here is some code - this method is called whenever the user presses Ctrl-L or the lock timer elapses:
private void LockApplication()
{
try
{
// Stop the timer so we don't get any more elapsed events whilst we are waiting
// for a user to respond to the lockdown dialog. In addition stop the callout reminder
// time as once we have locked we don't want that doing it's thing.
lockdownTimer.Stop();
calloutsReminderTimer.Stop();
// Clone the current identity so we can check it later.
var previousIdentity = (CudosIdentity)BOUtilities.CurrentIdentity.Clone();
// Show lockdown form.
System.Windows.Forms.DialogResult result;
using (var lockForm = new Forms.applicationLockedForm())
result = lockForm.ShowDialog(this);
if (result == DialogResult.OK)
{
// Did we unlock with a different login?
if (!previousIdentity.Equals(BOUtilities.CurrentIdentity))
{
// Yes, so lose all changes.
CloseOpenForms();
if (_currentLoadSpec != null)
_currentLoadSpec.CancelContent();
}
RefreshLockTimerSetting(null);
}
else
fileExitMenuItem.PerformClick();
}
catch (Exception ex)
{
Helper.LogError(ex);
}
finally
{
lockdownTimer.Start();
calloutsReminderTimer.Start();
}
}
This is the code for the exit menu item:
private void fileExitMenuItem_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
When the following line in LockApplication method from above is called I get the NullReferenceException:
fileExitMenuItem.PerformClick();
[UPDATE 2] Call stack info when the above line is executed:
[External Code]
Cudos.exe!Cudos.mainForm.LockApplication() Line 1132 + 0x10 bytes C#
Cudos.exe!Cudos.mainForm.fileLockCudosMenuItem_Click(object sender, System.EventArgs e) Line 1594 + 0x8 bytes C#
[External Code]
Cudos.exe!Cudos.mainForm.Main() Line 1880 + 0x1d bytes C#
[External Code]
I am not sure, but I will try to remove the restart of the timers if you call the Perform_Click.
The Tick event could be called when there is no more the application because you call Application.Exit().
private void LockApplication()
{
try
{
lockdownTimer.Stop();
calloutsReminderTimer.Stop();
.....
if (result == DialogResult.OK)
{
......
lockdownTimer.Start();
calloutsReminderTimer.Start();
}
else
fileExitMenuItem.PerformClick();
}
catch (Exception ex)
{
Helper.LogError(ex);
lockdownTimer.Start();
calloutsReminderTimer.Start();
}
// remove the finally clause
}
In the end I gave up and just hacked it by changing the fileExitMenuItem.PerformClick() to Application.Exit(). So I still don't have any idea why it was throwing the exception but it at least now works. I guess if I put more logic into the fileExitMenuItem click handler I will just have to remember to extract it into a method and update this hack to call that method to.
I am working on a wpf .My requirement is to change selection of tab according to user confirmation it means every time when user changes tab a message box opens and confirm with user whether he wants to change the tab or not.
But problem with me is when I press no first time it works fine .but after that on second time it asks two times for user confirmation
can anyone help me to solve this ?
private void tabcontrol_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
try
{
if (handleSelection && e.OriginalSource == tbUserProfileMainControl)
{
//Ask user for change
if (isUserAllowedToChanged)
{
int currentIndex = (tabcontrol.SelectedIndex);
GeneralDeclaration.currentSelectedTabIndex = currentIndex;
LoadUserControl(GeneralDeclaration.currentSelectedTabIndex);
}
else
{
//e.Handled = true;
handleSelection = false;
tbUserProfileMainControl.SelectedIndex = Math.Abs(tbUserProfileMainControl.SelectedIndex - 1);
}
}
handleSelection = true;
}
catch (Exception ex)
{
//
}
}
It sounds like you're adding handlers during the click event itself. This causes your subsequent click to perform the action one more time (3rd click 3 times, 4th click 4 times, etc).
Check how you bind the event to the handler and check where you are defining the handler itself. You're doing something twice that should only be done once.
This is my estimation based on your findings, without code, I'm just taking a wild stab in the dark.
i'm building a win App and in that, i'm having a textBox which is get filled dynamically, and i have a checkBox, when checkBox.Checked=true all the message boxes in my app will get pop'd
(not all at a time, just confirmation msg's whereever i hv coded it, one by one).
my problem is when checkBox is checked, my TextBox.Text is getting filled its data but when that checkBox is unchecked, TextBox.text is not getting filled with data, wierd thing is when i tried to debug it, TextBox.Text is showing the text, but on gui TextBox.Text is not filled, now where`s data ?
public void Recharge()
{
txtTransactionMsgDelegate(Tm) // this is delegate function which fills the text
//textbox.text=tm; i tried this one too,but no use
}
if (Program.AutoManual == "Auto")
{
if (chkShowMsg.Checked)
{
if (returnRows < 1)
MessageBox.Show(Program.StatusMessage + " But Local Db Failed, NOTEDOWN IN NOTEBOOK");
else
MessageBox.Show(Program.StatusMessage + " And Local Db update SuccessFul, RUN UPDATE RECHARGE LATER");
}
}
Delegate Function:
// m using this delegate b'coz my above function i.e Recharge() is under BackGroundWorker Thread i.e BackGroundWorker_DoWork() event;
private void txtTransactionMsgDelegate(string Text)
{
if (txtTransactionMsg.InvokeRequired)
{
txtTransactionMsg.Invoke(new Action(delegate() { txtTransactionMsgDelegate(Text); }));
}
else
txtTransactionMsg.Text = Text;
}
To make sure the textbox is updated on the GUI you should call txtTransactionMsg.Refresh();