Rewrite: I'm writing a program to get a better understanding of C# and taking user input in. Right now I'm using WFA in C# with a textbox where I put the text of what I want pasted/typed out. Then I have two other boxes that have an interval input and a amount input. Everything worked perfectly fine until I added the amount input, I've added a while loop to a timer that is used to type/paste the text. However, for some reason that I'm not sure of.. The program disregards any input for the interval.
I have it basically setup like this
private void timerPaste_Tick(object sender, EventArgs e)
{
interval = Int32.Parse(interNum.Text);
timerPaste.Interval = interval;
if (typeModebool == true && pasteModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
if (pasteModebool == true && typeModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
}
something like that..?
timerPaste.Elapsed += OnTickEvent;
private async void OnTickEvent(Object source,EventArgs e)
{
interval = Int32.Parse(interNum.Text);
timerPaste.Interval = interval;
if (typeModebool == true && pasteModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
if (pasteModebool == true && typeModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
}
I actually was able to fix this, the problem was that the while loop listened to the timer the first time, then after that just started going off on it's own. I switched it to a if, with an else statement and everything works as intended now.
int i = 0;
private void timerPaste_Tick(object sender, EventArgs e)
{
if (typeModebool == true && pasteModebool == false) //Check what mode is being used
{
if (i < amount) //If runs until i == amount
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
else
{
timerPaste.Enabled = false;
}
}
if (pasteModebool == true && typeModebool == false)
{
if (i < amount)
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
else
{
timerPaste.Enabled = false;
}
}
}
Related
So I am trying to make a bot application, trying to see how I can do certain things in c#. I am not trying to cheat or so, it is a mobile game that I am running on a emulator. This is not an application that I am trying to sell or in any way profit from, this is simply a task for me to learn how to do these kind of things.
Any how, when I launch the application the memory goes up to 16 mb instantly, also I am trying to make a loop until a stop button has been clicked.
I make functions for every single action and I am using a timer to run all the functions to scan if a pixel gets detected, but the application is running slowly and taking up a lot of memory, I feel like this kind of "looping" is not the proper way to do this kind of action, I have tried the while method as well.
Anybody who is willing to tell me what I am doing?
Pastebin
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
// Checking if we entered Dragon's B10
if (inDungeon == false)
{
GoToDungeon();
}
// Starting battle
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2078, 61); // 0xF1EECF
if (autoSumPoint == 0xF1EECF)
{
StartBattle();
}
else
{
GoToDungeon();
}
// Starting auto-play
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2296, 969); // 0xFFFFFF
if (autoSumPoint == 0xFFFFFF)
{
AutoCheck();
}
// Starting battle
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2755, 489); // 0xF1EECF
if (autoSumPoint == 0xF1EECF)
{
PauseCheck();
}
// Checking for defeat
if (defeatChecked == false)
{
DefeatCheck();
}
// Checking for defeat
if (defeatChecked == false)
{
DefeatCheck();
}
// Checking for victory
if (victoryChecked == false)
{
VictoryCheck();
}
// Checking for replay
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2602, 587); // 0xF3C761
if (autoSumPoint == 0xF3C761)
{
ReplayCheck();
}
// Checking for refill
if (energyRefilled == false)
{
RefillCheck();
}
}
}
I would consider changing the delay between each tick of the timer, so that it doesn't burn up your CPU.
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
// Checking if we entered Dragon's B10
if (inDungeon == false)
{
GoToDungeon();
}
// Starting battle
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2078, 61); // 0xF1EECF
if (autoSumPoint == 0xF1EECF)
{
StartBattle();
}
else
{
GoToDungeon();
}
// Starting auto-play
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2296, 969); // 0xFFFFFF
if (autoSumPoint == 0xFFFFFF)
{
AutoCheck();
}
// Starting battle
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2755, 489); // 0xF1EECF
if (autoSumPoint == 0xF1EECF)
{
PauseCheck();
}
// Checking for defeat
if (defeatChecked == false)
{
DefeatCheck();
}
// Checking for defeat
if (defeatChecked == false)
{
DefeatCheck();
}
// Checking for victory
if (victoryChecked == false)
{
VictoryCheck();
}
// Checking for replay
autoSumPoint = AutoIt.AutoItX.PixelGetColor(2602, 587); // 0xF3C761
if (autoSumPoint == 0xF3C761)
{
ReplayCheck();
}
// Checking for refill
if (energyRefilled == false)
{
RefillCheck();
}
}
System.Threading.Thread.Sleep(1000)//causes it to wait 1 second after each tick before the next one to reduce CPU usage
}
See if that helps you!
Techcraft7 :)
I have a RichTextBox for which I have created a "scroll through sent messages" feature. This means that if the user sends (by pressing enter) any messages (up to 20), the user can then scroll through them in order by pressing the up/down arrows on the keyboard. This part works as intended.
The issue is: I want to select all text in the RichTextBox after each arrow press.
Here is my code:
private void rtb_inputField_KeyDown(object sender, KeyEventArgs e) {
RichTextBox inputField = (RichTextBox)sender;
string userInput = inputField.Text.Trim();
string[] clientScriptString = userInput.Split(' ');
string modifiedInput = string.Empty;
string macroString = string.Empty;
//Other code...
if (e.KeyData == Keys.Enter) {
//Other code..
if ((client != null) && (client.Connected)) {
macroString = runInputThroughMacroDictionary(userInput);
sendInputToServer(macroString); //Sent message
}
addSentMessageToHistory(userInput); //Added sent message to history
e.Handled = true;
e.SuppressKeyPress = true;
hasUpBeenPressed = false;
}
if ((e.KeyData == Keys.Up) || (e.KeyData == Keys.Down)) {
scrollThroughSentMessages(e);
rtb_inputField.SelectAll();
}
}
private void scrollThroughSentMessages(KeyEventArgs e) {
if (sentMessageHistory.Count > 0) {
if (e.KeyData == Keys.Up) {
if (!hasUpBeenPressed) {
scrollThroughMsgHist = sentMessageHistory.Count - 1;
}
else {
scrollThroughMsgHist--;
if (scrollThroughMsgHist < 0) {
scrollThroughMsgHist = sentMessageHistory.Count - 1;
}
}
hasUpBeenPressed = true;
}
if ((e.KeyData == Keys.Down) && (hasUpBeenPressed)) {
scrollThroughMsgHist++;
if ((scrollThroughMsgHist >= 20) || (scrollThroughMsgHist > (sentMessageHistory.Count - 1))) {
scrollThroughMsgHist = 0;
}
}
rtb_inputField.Text = sentMessageHistory[scrollThroughMsgHist];
}
}
private void addSentMessageToHistory(string message) {
int currentAmountOfMessage = sentMessageHistory.Count;
if (!string.IsNullOrWhiteSpace(message)) {
if (currentAmountOfMessage == 0) {
sentMessageHistory.Add(message);
}
else {
if (sentMessageHistory[currentAmountOfMessage - 1] != message) {
if (currentAmountOfMessage == 20) {
sentMessageHistory.RemoveAt(0);
}
sentMessageHistory.Add(message);
}
}
}
}
The first method does a whole bunch of things. (I removed some of the irrelevant code.) It adds the last sent message to sentMessageHistory (which is a List) via the third method. It also listens for Up/Down, and calls upon the second method.
The second method "scrolls through" each of the entries in the sentMessageHistory -List, and writes it in the RichTextBox. All of this works fine.
What doesn't work is the rtb_inputField.SelectAll(); after the second method has run.
I found the solution. I added the following:
if ((e.KeyData == Keys.Up) || (e.KeyData == Keys.Down)) {
scrollThroughSentMessages(e);
e.Handled = true;
e.SuppressKeyPress = true;
rtb_inputField.SelectAll();
}
I don't know what e.Handled and e.SupressKeyPress does, but it works. So now my code successfully selects the text after "scrolling through history".
Hi all firstly thanks for taking the time to read. I am trying to clean up my code and make it more efficient and want to put some code into one method that will be use for both boutton clicks.
private void buttonNext_Click(object sender, EventArgs e)
{
y += 1;
QuestionsFromDb.qid += 1;
qdb.MultiChoiceFunctionsLight();
Questions();
FlagColour();
//Shows visability for next and previous buttons
if (y >= 9)
{
buttonNext.Visible = false;
buttonEndQuiz.Visible = true;
}
if (y == 1)
{
buttonPrevious.Visible = true;
}
}
private void buttonNext_Click(object sender, EventArgs e)
{
y += 1;
QuestionsFromDb.qid += 1;
qdb.MultiChoiceFunctionsLight();
Questions();
FlagColour();
//Shows visability for next and previous buttons
if (y >= 9)
{
buttonNext.Visible = false;
buttonEndQuiz.Visible = true;
}
if (y == 1)
{
buttonPrevious.Visible = true;
}
}
So as you can see i hate repeating my code but with the Button_Click methods im not sure how to set the click to true, false or clicked. This is my idea.
private void ButtonClicked()
{
if(buttonNext_Click == SOMETHING!)
{
if (y >= 9)
{
buttonNext.Visible = false;
buttonEndQuiz.Visible = true;
}
if (y == 1)
{
buttonPrevious.Visible = true;
}
}
else
{
//Shows visability for next and previous buttons
if (y == 0)
{
buttonPrevious.Visible = false;
}
if (y < 10)
{
buttonNext.Visible = true;
}
}
}
The code works fine but im am starting to get code OCD i am under the impression that doing it this way will help keep my code more readable and maybe make processing and memory run more effricient. Any ideas are greatly appreciated. Thanks
Based on:
C# windows form & using WMPLib
The Problem:
when pressing next or prev button too fast, the apps will freeze a bit (uncontrollable).
The Code:
private void next_event()
{
_paused = false;
if (list[current_index].Rows.Count != 0 && _playing == true)
{
if (option.random.Checked == true)
{
nextRandom(1);
}
else if (option.order.Checked == true)
{
if (list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) == list[current_index].Rows.Count - 1)
{
setNowPlaying((Guid)list[current_index].Rows[0].Cells["Key"].Value);
}
else
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) + 1].Cells["Key"].Value);
}
}
seek_bar.Value = 0;
play();
}
}
private void prev_event()
{
_paused = false;
if (list[current_index].Rows.Count != 0 && _playing == true)
{
if (option.random.Checked == true)
{
nextRandom(2);
}
else if (option.order.Checked == true)
{
if (list[current_index].CurrentRow.Index == 0)
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.Count - 1].Cells["Key"].Value);
}
else
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) - 1].Cells["Key"].Value);
}
}
seek_bar.Value = 0;
play();
}
}
private void play() // play
{
button3.Text = "Pause";
dmp_status.Text = "Playing...";
_paused = false;
if (list[current_index].Rows.Count != 0)
{
if (File.Exists(_musicData[_NowPlaying].Cells["FileLocation"].Value.ToString()))
{
if (_playing == true) wmp.controls.stop();
if(wmp != null) wmp.close();
wmp = new WMPLib.WindowsMediaPlayer();
wmp.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(PlayStateChange);
seek_bar.Value = 0;
setNowPlayingLabel(_musicData[_NowPlaying]);
if (!_musicData.ContainsKey(_LastPlaying)) _LastPlaying = Guid.Empty;
setNowPlayingColor(_musicData[_LastPlaying],_musicData[_NowPlaying]);
//wmp.URL = list[current_index].CurrentRow.Cells["FileLocation"].Value.ToString();
wmp.URL = _musicData[_NowPlaying].Cells["FileLocation"].Value.ToString();
wmp.controls.play();
wmp.settings.rate = wmp_rate;
wmp.settings.volume = volume_pos;
if (_playing == false) _playing = true;
}
else
{
next_event();
}
}
}
The Question:
I have hard time figuring why they need a delay(freeze) before playing each music, this making a problem when user press next button consecutively.
I think it is due to reentry. Happened when subsequent events are fire while the first event hasn't complete. To prevent this:
// add this line to your class member
private Object syncRoot = new Object();
// add this block to your next_event() method
if (!Monitor.TryEnter(syncRoot)) return;
try {
// add your existing code here
}
finally {
Monitor.Exit(syncRoot);
}
For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M
namespace PasswordGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bcopy_Click(object sender, EventArgs e)
{
if (passwordGenBox.Text.Length != 0)
{
Clipboard.SetText(passwordGenBox.Text);
}
else
{
MessageBox.Show("No Password Generated.", "Copy Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void bclear_Click(object sender, EventArgs e)
{
passwordGenBox.Text = "";
}
private void lengthSlider_Scroll(object sender, EventArgs e)
{
sliderLength.Text = lengthSlider.Value.ToString();
int str = lengthSlider.Value;
bool scheck = symCheck.Checked;
bool ncheck = numbersCheck.Checked;
//1-10 no symbols or numbers
if (str > 0 && str <= 10)
{
strLabel.Text = "Week";
}
//1-10 symbols no numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == false)
{
strLabel.Text = "Alright";
}
//1-10 no symbols but numbers
if (str > 0 && str <= 10 && scheck == false && ncheck == true)
{
strLabel.Text = "Week";
}
//1-10 symbols & numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == true)
{
strLabel.Text = "Okay";
}
}
private void bgen_Click(object sender, EventArgs e)
{
int pwlength = lengthSlider.Value;
bool symbols = false;
bool numbers = false;
if (symCheck.Checked && numbersCheck.Checked)
{
symbols = true;
numbers = true;
}
else if (symCheck.Checked && numbersCheck.Checked == false)
{
symbols = true;
numbers = false;
}
else if (symCheck.Checked == false && numbersCheck.Checked)
{
symbols = false;
numbers = true;
}
else
{
symbols = false;
numbers = false;
}
Generator gen = new Generator(pwlength, symbols, numbers);
}
}
}
Well, it's quite difficult to understand what you're actually asking here but the reason your ProgressBar isn't updating is that you're not actually telling it to update unless you move the slider.
Notice how you have all your logic for whether the password is "alright, weak or okay" on the Slide event of your "lengthSlider" component. However, nowhere in that code do you set the value of the ProgressBar - that appears to be done on the "bgen_Click" event which I assume is the generate password button?
In order to update the GUI when you operate the individual controls you need to call the appropriate code. I would suggest you put all your logic into meaningful functions and call them as needed.
Personally I'd have something along these lines:
GetPasswordStrengthString(); - check for symbols and numbers checkbox.checked and the length to return an appropriate string for the "strLabel" label.
CalculateStrengthBarLength(); - all your logic to determine the length of the ProgressBar
These would then be called wherever you want them to take effect. For example, on the CheckedChanged event of the symbols and numbers checkboxes as when that changes you want to see it reflected in the ProgressBar.