none
how to acess the textbox in form1.cs using the program.cs RRS feed

  • Question

  • Hi Geeks,
                   i have a problem in updating a textbox that is used in a class in  form1.cs .Textbox should get updated by a message sent from the program.cs.the idea is i have to chnage the message in the textbox based on the condition in the code present in the program.cs,as i cant acess the textbox object craeted in the form1.cs class...plz help me in this regard of using the Ui component in the program.cs....

    Thanks in Advance.....
    Regards /-\\/|/\//-\S|-| "Life IS An opportunity To prove Ur Self"
    Monday, February 1, 2010 10:40 AM

Answers

  • Hi Friend,
      I think you want to show a text from program.cs in a textbox which is owned by form1.cs.
    If the form1.cs is started from program.cs, it is easy. But, Application.Run is a synchronous call.
    so after executing that only the other things, proceeded, will execute. In this case you will have to implement asynchronous calls.
    You can expose a public property or a method and access it from the program.cs file. But it must be thread safe.

    program.cs

    Form1 frm1=new Form1();
    Application.Run(frm1);
    frm1.UpdateText("your Message");

    Form1.cs

    public void UpdateText(string message)
    {
      textbox1.text=message;
    }

    This wont work strait away, because the update text method will execute when you close the form. Change it accordingly for an asynchronous execution.

    -- Thanks Ajith R [Mark the best posts as Answers.]
    • Marked as answer by hsaniva_k Monday, February 1, 2010 1:03 PM
    Monday, February 1, 2010 11:06 AM
  • Hi, AvinashReddy:
        I am not quite sure about what you mean by "an event in the program". But this is technically doable.
        You could add delegate and event to your program.cs and then register to it with corresponding event handler in your form1.cs. Like the following code snippet:

    Program.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace UpdateFormControl
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Form1 myform = new Form1();
                myevent += myform.textBox1_handler;
                myevent();
                Application.Run(myform);
            }
            public static event mydelegate myevent;
        }
        public delegate void mydelegate();
    }

    Form1.cs:

    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;
    
    namespace UpdateFormControl
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            public void textBox1_handler()
            {
                textBox1.Text = "myevent from program.cs";
            }
        }
    }

        Thouth works just fine, it seems a little weird to me.
        Wish this could help you.

    "May the Solution be with you."
    Thanks,
    Sam
    • Edited by SamAgain Tuesday, February 2, 2010 3:20 AM refine
    Tuesday, February 2, 2010 3:20 AM

All replies

  • Hi Friend,
      I think you want to show a text from program.cs in a textbox which is owned by form1.cs.
    If the form1.cs is started from program.cs, it is easy. But, Application.Run is a synchronous call.
    so after executing that only the other things, proceeded, will execute. In this case you will have to implement asynchronous calls.
    You can expose a public property or a method and access it from the program.cs file. But it must be thread safe.

    program.cs

    Form1 frm1=new Form1();
    Application.Run(frm1);
    frm1.UpdateText("your Message");

    Form1.cs

    public void UpdateText(string message)
    {
      textbox1.text=message;
    }

    This wont work strait away, because the update text method will execute when you close the form. Change it accordingly for an asynchronous execution.

    -- Thanks Ajith R [Mark the best posts as Answers.]
    • Marked as answer by hsaniva_k Monday, February 1, 2010 1:03 PM
    Monday, February 1, 2010 11:06 AM
  • you can also make a constructor for the form, so you can pass a parameter

    Public Sub New(ByVal txtMessage As String)
      Me.TextBox1.Text = txtMessage
    End Sub
    in the same way, you can pass a list of parameter (if the sign is ByVal args As Strings)
    please, mark this as answer if it is THE answer
    ----------------
    Diego Cattaruzza
    Microsoft MVP - Visual Basic: Development
    blog: http://community.visual-basic.it/Diego
    web site: http://www.visual-basic.it
    Monday, February 1, 2010 11:17 AM
  • Hi GEEKs,
                 i am new to this C# and please help me with the following problem..
    i need to update a Textbox created in form1.cs when an event in the program.cs occurs..plz help me with a small codesnippet else provide me with appropriate links......
    thanks in advance.
    Regards /-\\/|/\//-\S|-| "Life IS An opportunity To prove Ur Self"
    • Merged by SamAgain Tuesday, February 2, 2010 4:15 AM duplicate
    Monday, February 1, 2010 2:24 PM
  • I don't understand why you want this. I'm pretty sure you're wrong in this scenario.

    You can add an handler to the event you want be adverted with (for example)

    supposing you have in your program.cs a Sub named Form1_Closed, that has this sign:

    Private Sub Form1_Closed(ByVal sender as object, ByVal e As Eventargs)

    you can do this:

        Form1 frm = new Form1(yourTextForTheTextbox);
       
        frm.FormClosed += Form1_Closed;
       
        Application.Run(frm);

    But, IMHO, you'd better change your mind.


    please, mark this as answer if it is THE answer
    ----------------
    Diego Cattaruzza
    Microsoft MVP - Visual Basic: Development
    blog: http://community.visual-basic.it/Diego
    web site: http://www.visual-basic.it
    Monday, February 1, 2010 3:40 PM
  • Hi, AvinashReddy:
        I am not quite sure about what you mean by "an event in the program". But this is technically doable.
        You could add delegate and event to your program.cs and then register to it with corresponding event handler in your form1.cs. Like the following code snippet:

    Program.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace UpdateFormControl
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Form1 myform = new Form1();
                myevent += myform.textBox1_handler;
                myevent();
                Application.Run(myform);
            }
            public static event mydelegate myevent;
        }
        public delegate void mydelegate();
    }

    Form1.cs:

    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;
    
    namespace UpdateFormControl
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            public void textBox1_handler()
            {
                textBox1.Text = "myevent from program.cs";
            }
        }
    }

        Thouth works just fine, it seems a little weird to me.
        Wish this could help you.

    "May the Solution be with you."
    Thanks,
    Sam
    • Edited by SamAgain Tuesday, February 2, 2010 3:20 AM refine
    Tuesday, February 2, 2010 3:20 AM
  • Hi,

    I am also using the program.cs file. If the user presses the Alt and printscreen keys  a message box

    comes up and says you pressed the Alt-printscreen keys. That is good. But I want to increment a counter

    every time the uses press the Alt-printscreen keys. This should increment a number in a textbox in a form called

    form2. This runs in the program.cs file. I have the same type of form code as above.

     

    If I uncomment the code that is above it give me errors:

    Error 1 Operator '+=' cannot be applied to operands of type 'ScreenShotApp.Program.mydelegate' and 'method group' C:\myworkpc2\Projects\ScreenShotApp\Backup2\ScreenShotApp\Program.cs 27 13 ScreenShotApp

    Error 2 No overload for 'textBox1_TextChanged_2' matches delegate 'ScreenShotApp.Program.mydelegate' C:\myworkpc2\Projects\ScreenShotApp\Backup2\ScreenShotApp\Program.cs 27 24 ScreenShotApp


    So here is the code and if anybody can shed some light on this it would be great!

    //Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.Diagnostics;

    namespace ScreenShotApp
    {
        static class Program
        {
           
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
           
            
            static void Main()
            {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Form2 myform = new Form2();
                
                
                myevent += myform.textBox1_TextChanged_2;
                myevent();

                _hookID = SetHook(_proc);
                //Application.Run(new Form1());
                Application.Run(myform);
                UnhookWindowsHookEx(_hookID);  

            }

            public static event mydelegate myevent;
          
         public delegate void mydelegate();
        
        
        
            /****************************************/
            private const int WH_KEYBOARD_LL = 13;
            //private const int WH_KEYBOARD_LL = 13;  
            private const int WM_KEYDOWN = 0x0100;
            private const int VK_F1 = 0x70;
            private static LowLevelKeyboardProc _proc = HookCallback;
            private static IntPtr _hookID = IntPtr.Zero;
            
            

            private static IntPtr SetHook(LowLevelKeyboardProc proc)
            {
                using (Process curProcess = Process.GetCurrentProcess())
                using (ProcessModule curModule = curProcess.MainModule)
                {
                    return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                        GetModuleHandle(curModule.ModuleName), 0);
                }
            }
            
            private delegate IntPtr LowLevelKeyboardProc(
                int nCode, IntPtr wParam, IntPtr lParam);

            private static IntPtr HookCallback(
                int nCode, IntPtr wParam, IntPtr lParam)
            {
                
                if (nCode >= 0)
                {
                    Keys number = (Keys)Marshal.ReadInt32(lParam);
                    if (number == Keys.PrintScreen)
                    {
                        if ((wParam == (IntPtr)260 && Keys.Alt == Control.ModifierKeys && number == Keys.PrintScreen))
                        {
                          
                               MessageBox.Show("You pressed alt + print screen");
                            
                            //This is the count stuff and I know I can't access the textbox this way but the count stuff is what i need to                                  //increment the textbox number.
                            int count = 0;
                            count++;
                            int noofcount = count;
                            /
                            //try
                            //{
                              
                                //{
                              
                                //}
                                //if (count == 0)
                                    //MessageBox.Show("No Screen Shots Taken");
                                    //textBox1.Text = "0";
                           
                                //else
                                //MessageBox.Show("Number of Screen Shots Taken: " + count);
                                //{
                                    //textBox1.Text = ("" + count);
                                    //textBox1.Hide();
                                //}
                            //}
                           // catch (Exception ex)
                            //{
                                //MessageBox.Show(ex.ToString());
                            //}
                            //finally
                            //{

                            //}

                           

                        }
                       
                    }

                }
                return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);

            }

            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr SetWindowsHookEx(int idHook,
                LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool UnhookWindowsHookEx(IntPtr hhk);

            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
                IntPtr wParam, IntPtr lParam);

            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr GetModuleHandle(string lpModuleName);

           

        }

    }

    Tuesday, July 13, 2010 5:48 PM
  • Hi Bro,

    Your code is not working exactly, showing error like

    Can't implicitly convert void to <g class="gr_ gr_17 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="17" id="17">mydelegate</g> at Myevent+ line", 

    is there any solution for this.

    Thanks,

    Srikanth Chila


    Friday, March 1, 2019 6:21 AM
  • Hi bro,

    How to call asynchronously??

    Thanks,

    Srikanth

    Friday, March 1, 2019 6:48 AM