dcsimg
Results 1 to 19 of 19
  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Question Imitating Console.ReadLine() with a RTB & TXT

    I have two controls on a windows form.

    rtbOutput = RichTextBox
    txtInput = TextBox

    When the KeyDown event is triggered, if e.Keycode == Keys.Enter then a combination of a Switch block and if statements are used to process what the user entered in the textbox (txtInput). If for example it equals "exit" then the application will exit: Application.Exit();

    If it were another command for example 'time', then "The time is ...." would be appended on a new line of rtbOutput. However how would I create my own version of Console.ReadLine()? For example when the user types 'exit', instead of just exiting the application, a new line is added to rtbOutput: "Are you sure you would like to exit? (Y/N)". Then the user has the option of typing y/n to exit or not exit the application.

    This is simple in a Console application.

    Code:
    If(Console.ReadLine() == "exit"){
    Console.WriteLine("Are you sure you would like to exit?");
    If(Console.ReadLine() == "n"){
    return;
    }
    Application.Exit();
    }
    When it comes to using a richTextBox and a textBox how can I 'Read' the next line the user enters and continue with my if statement, processing the response, just like I would do with a console application?

  2. #2
    Frenzied Member Lightning's Avatar
    Join Date
    Oct 2002
    Location
    Eygelshoven
    Posts
    1,611

    Re: Imitating Console.ReadLine() with a RTB & TXT

    What exactly is the problem? You have all the pieces
    VB6 & C# (WCF LINQ) mostly


    If you need help with a WPF/WCF question post in the NEW WPF & WCF forum and we will try help the best we can

    My site

    My blog, couding troubles and solutions

    Free online tools

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,681

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Quote Originally Posted by noahssite View Post
    When it comes to using a richTextBox and a textBox how can I 'Read' the next line the user enters and continue with my if statement, processing the response, just like I would do with a console application?
    You can't, unless you have that code executing on a secondary thread.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Imitating Console.ReadLine() with a RTB & TXT

    a little hint: catch the event when the text changes. now, if the character is a carriage return, then read the previous line and use your switch block to determine what that line stated. or even better, use the keydown event args to determine what key was pressed.



    example:

    Drop a textbox on the form.
    View the events of the textbox in the properties window, and double click the KeyDown event to subscribe to the event and for the application to handle that event.

    the textbox exposes a string[] array of lines - a collection of lines in the textbox. we need to access the previous line after you hit enter to know what the user wrote.

    Then, the code is something like the following:

    Code:
    void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
       if (e.KeyData == Keys.Return || e.KeyData = Keys.Enter)
       {
          string previousLine = this.textbox1.Lines[this.textbox1.Lines.Count() - 1];
          // execute your switch statement here, checking the previousLine
       }
    }
    now, re-reading your post, I guess you want to determine the answer/response from the user's question that YOU programmatically give?
    I guess by using the same method/approach outlined above, you can read what the previous line has (in this case, the example is "are you sure?") then since they pressed enter (the user), then you do your validation there.

    does this help?

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  5. #5

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    I was thinking of a few ways of accomplishing this.. One of my major issues is efficiency...

    I'm going to work with a separate thread to handle the input of the text box.

    I'll post back once I've accomplished my goal (or if I fail..).

    EDIT: I think I'm just going to make a thread (like jmc said) that works like Console.ReadLine(), it would wait for the user to enter a new line and then return a value, I'm going to have to read a bit more about threads since I'm not sure how I can make it return a value.. Like I said before I'll post back my progress.
    Last edited by noahssite; Jul 22nd, 2010 at 10:58 PM.

  6. #6
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Imitating Console.ReadLine() with a RTB & TXT

    sure but question is, why do you need a thread? what is the reasoning behind it? maybe im missing something? Threads really are used for heavy tasking without blocking the UI.

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  7. #7

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Quote Originally Posted by Techno View Post
    sure but question is, why do you need a thread? what is the reasoning behind it? maybe im missing something? Threads really are used for heavy tasking without blocking the UI.
    Isn't that the point? If I have the If...Then statement on hold waiting for a value to be returned won't it 'pause' the UI? Well that's if I use a loop, which wouldn't be very good. I'm going to try a few things. Whatever comes to my head..

  8. #8
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Imitating Console.ReadLine() with a RTB & TXT

    from what I understood and please DO correct me, you are going to be using a textbox for input. textbox does not block the UI thread for input. therefore, no need for a thread.

    the solution provided earlier will monitor the user's keypress (again doesnt block the thread) and then you do your conditions in there depending on the keystroke entered and what the functionality of your software is.

    you may have switch/if statements but they do not block the thread, not unless you are using some horrendous loop, looping through endlessly, which won't be the case here.

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  9. #9

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Quote Originally Posted by Techno View Post
    from what I understood and please DO correct me, you are going to be using a textbox for input. textbox does not block the UI thread for input. therefore, no need for a thread.

    the solution provided earlier will monitor the user's keypress (again doesnt block the thread) and then you do your conditions in there depending on the keystroke entered and what the functionality of your software is.

    you may have switch/if statements but they do not block the thread, not unless you are using some horrendous loop, looping through endlessly, which won't be the case here.
    So no more threads! That's going to make it easier.

  10. #10

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Access a RichTextBox from another thread.

    How do I access a control such as a RichTextBox from a thread it wasn't created on?

    EDIT: More specifically what I want is to retrieve the Lines.Length of the RichTextBox.
    Last edited by noahssite; Jul 24th, 2010 at 02:48 PM.

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,681

    Re: Access a RichTextBox from another thread.

    Follow the CodeBank link in my signature and check out my post on Accessing Controls From Worker Threads. It shows you how to pass data into and get data out of controls from worker threads. A lot of people seem to stumble at the first step: create a method that does what you want without multi-threading. In your case, that would look like this:
    csharp Code:
    1. private int GetRichTextBoxLineCount()
    2. {
    3.     return this.RichTextBox1.Lines.Length;
    4. }
    I'll let you implement the rest of the steps from there.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Access a RichTextBox from another thread.

    Thanks.

    It's not working though.. When it reaches:
    Code:
    if (this.rtbOutput.InvokeRequired)
    The thread terminates, when I step though the code. The thread shouldn't terminate until all my code is done executing. When I click F5 to Run/Debug the program there is no sign that the thread is exiting...
    Last edited by noahssite; Jul 25th, 2010 at 06:24 PM.

  13. #13
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Access a RichTextBox from another thread.

    can you give the full code you are using?
    how do you know if the thread is being terminated?

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  14. #14
    Super Moderator Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,335

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Threads Merged At OP's Request
    Please use [Code]your code goes in here[/Code] tags when posting code.
    When you have received an answer to your question, please mark it as resolved using the Thread Tools menu.
    Before posting your question, did you look here?
    Got a question on Linux? Visit our Linux sister site.
    I dont answer coding questions via PM or EMail. Please post a thread in the appropriate forum section.

    Creating A Wizard In VB.NET
    Paging A Recordset
    What is wrong with using On Error Resume Next
    Good Article: Language Enhancements In Visual Basic 2010
    Upgrading VB6 Code To VB.NET
    Microsoft MVP 2005/2006/2007/2008/2009/2010/2011/2012/Defrocked

  15. #15

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Here is the source code for my own version of the Console.ReadLine(). I ended up using threads anyway. I asked for these two 'forum threads' to be merged since the goal is the same.

    I don't usually use System.Threading.Threads so I may be using it wrong.

    Also while the thread (more specifically the loop) is running the UI is blocked, the user can't enter yes or no into the textbox.

    Code:
       Thread threadConvo;
       string ReadLineResponse = "";
       public delegate string GetRtbOutputLineValueInvoker(int i);
       public delegate int GetRtbOutputLineLengthInvoker();
       
       private void txtInput_KeyUp(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    ProcessCommand(txtInput.Text);
                }
            }
            private void ProcessCommand(string cmd)
            {
                txtInput.Clear();
                Output(cmd, 1);
                switch (cmd)
                {
                    case "exit":
                        Output("Exiting...", 0);
                        Application.Exit();
                        break;
                    default:
                        //If..Then...Statements
                        if (cmd.StartsWith("delete"))
                        {
                            //How to Console.ReadLine()
                            threadConvo = new Thread(ReadLine);
                            threadConvo.IsBackground = true;
                            TimeSpan ts = new TimeSpan(0, 3, 0);
                            Output("Are you sure you would like to delete this file? (yes/no)", 0);
                            threadConvo.Start();
                            threadConvo.Join(ts);
                            if (ReadLineResponse == "yes")
                            {
                                Output(String.Format("Deleting {0}...", fi.FullName), 0);
                            }
                            else if (ReadLineResponse == "no")
                            {
                                Output("File deletion has been canceled.", 0);
                            }
                            else
                            {
                                Output("Invalid answer. 'No' has been presumed.", 0);
                                Output("File deletion has been canceled.", 0);
                            }
                        }
                        else
                        {
                            Output("The command '" + cmd.Trim() + "' is an unknown command.", 2);
                        }
                        break;
                }
            }
            public int GetRtbOutputLineLength()
            {
                if (this.rtbOutput.InvokeRequired)
                {
                    return (int)this.rtbOutput.Invoke(new GetRtbOutputLineLengthInvoker(GetRtbOutputLineLength));
                }
                else
                {
                    return this.rtbOutput.Lines.Length;
                }
            }
            public string GetRtbOutputLineValue(int i)
            {
                if (this.rtbOutput.InvokeRequired)
                {
                    return (string)this.rtbOutput.Invoke(new GetRtbOutputLineValueInvoker(GetRtbOutputLineValue), i);
                }
                else
                {
                    return this.rtbOutput.Lines[i].ToString();
                }
            }
            private void ReadLine()
            {
                int currLineIndex = GetRtbOutputLineLength();
                while (GetRtbOutputLineLength() < currLineIndex + 1)
                {
                    if (GetRtbOutputLineLength() > currLineIndex)
                    {
                        ReadLineResponse = GetRtbOutputLineValue(currLineIndex);
                        //threadConvo.Abort();
                    }
                }
            }
    Note * Output() appends text to rtbOutput.
    Last edited by noahssite; Jul 26th, 2010 at 03:36 PM.

  16. #16
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: Imitating Console.ReadLine() with a RTB & TXT

    still doesnt make sense why you are using threads here

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  17. #17

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Quote Originally Posted by Techno View Post
    still doesnt make sense why you are using threads here
    What's the alternative?

  18. #18

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Quote Originally Posted by Techno
    a little hint: catch the event when the text changes. now, if the character is a carriage return, then read the previous line and use your switch block to determine what that line stated. or even better, use the keydown event args to determine what key was pressed.
    oh... I'll rewrite the code and see what I get..

  19. #19

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2008
    Posts
    1,754

    Re: Imitating Console.ReadLine() with a RTB & TXT

    Here is revised (no threading) code:

    Code:
            private void ProcessCommand(string cmd)
            {
                txtInput.Clear();
                Output(cmd, 1);
               if (rtbOutput.Lines.Length > 3)
                {
                    if (rtbOutput.Lines[rtbOutput.Lines.Length - 3].Contains("?"))
                    {
                        switch (rtbOutput.Lines[rtbOutput.Lines.Length - 3])
                        {
                            case "Response: Are you sure you would like to delete this file? (yes/no)":
                                if (cmd.Contains("yes"))
                                {
                                    Output(String.Format("Deleting {0}...", fi.FullName), 0);
                                }
                                else
                                {
                                    Output("File deletion has been canceled.", 0);
                                }
                                break;
                        }
                        return;
                    }
                }
                switch (cmd)
                {
                    case "time":
                        Output(DateTime.Now.ToString(), 0);
                        break;
                    case "cls":
                        rtbOutput.Clear();
                        break;
                    case "exit":
                        Output("Exiting...", 0);
                        Application.Exit();
                        break;
                    default:
                        //If..Then...Statements
                        if (cmd.StartsWith("delete"))
                        {
                           Output("Are you sure you would like to delete this file? (yes/no)", 0);
                        }
                        else
                        {
                            Output("The command '" + cmd.Trim() + "' is an unknown command.", 2);
                        }
                        break;
                }
            }
    I guess the Threading was over doing it.. However it would of minimized the amount of code used. The above way requires me to write code for the question and code for the answer..

    EDIT: Also 2 things I forgot to mention, Output outputs the string to rtbOutput attaching 'Response: ' or 'Command: ' to the beginning of the string. Also there is always a blank line at the end of the richtextbox.

    EDIT: The imitating the Console.ReadLine may have been resolved but for the future and out of curiosity, why wasn't my thread working when I used the approach with the thread?
    Last edited by noahssite; Jul 26th, 2010 at 04:23 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width


×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.