Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. windows not in focus

windows not in focus

Scheduled Pinned Locked Moved C#
questiontutorial
32 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M michaelgr1

    Yes, It works as keyboard amulator...

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #7

    Then you have a problem. all the Keyboard emulating BCRs I have seen read teh BC and just provide a datastream as if the barcode data had been typed by the user. For example, if the BC was 092939201610 then the BCR fakes teh keyboard keystrokes for '0' down, '0 up, '9' down, '9' up, etc. There is no way to tell if the real KB or the BCR provided the data, so would have to feed all keyboard data to your progam. As a user this would: 1) be very annoying and 2) look like a memory resident key logger. Your best bet is to talk to the manufacturer and see if they have done similar before.

    All those who believe in psycho kinesis, raise my hand.

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    H 1 Reply Last reply
    0
    • OriginalGriffO OriginalGriff

      Then you have a problem. all the Keyboard emulating BCRs I have seen read teh BC and just provide a datastream as if the barcode data had been typed by the user. For example, if the BC was 092939201610 then the BCR fakes teh keyboard keystrokes for '0' down, '0 up, '9' down, '9' up, etc. There is no way to tell if the real KB or the BCR provided the data, so would have to feed all keyboard data to your progam. As a user this would: 1) be very annoying and 2) look like a memory resident key logger. Your best bet is to talk to the manufacturer and see if they have done similar before.

      All those who believe in psycho kinesis, raise my hand.

      H Offline
      H Offline
      Heinzzy
      wrote on last edited by
      #8

      OriginalGriff wrote:

      Then you have a problem. all the Keyboard emulating BCRs I have seen read teh BC and just provide a datastream as if the barcode data had been typed by the user.

      I feel it's all ok. User such as a cashier isn't supposed to use a keyboard very often. So we can redirect BC stream to the textbox. In the textbox handler we can validate BC/user input. For example - user always start typing session with "A" char, else it's BC's chars.

      1 Reply Last reply
      0
      • M michaelgr1

        Yes, It works as keyboard amulator...

        M Offline
        M Offline
        MickCurley
        wrote on last edited by
        #9

        I can understand if you are developing a POS system you may want this input to be directed to the textbox. You could always try setting the KeyPreview to True on the Form. Then on the KeyPress you could try

            private void YourForm\_KeyPress(object sender, KeyPressEventArgs e)
            {
                ScannerFirstKeyValue = e.KeyChar.ToString();
        
                if (this.ActiveControl != this.YourTextBox)
                {
                    YourTextBox.AppendText(ScannerFirstKeyValue);
                }
                this.ActiveControl = YourTextBox;
            }
        

        This would ensure all input is placed in correct textbox. Remember if you have multiple textboxes this will be a problem!! Unless the BC Reader has some sort of prefix that can distinguish it from a keyboard.

        Regards Mick Curley :)

        L 1 Reply Last reply
        0
        • M MickCurley

          I can understand if you are developing a POS system you may want this input to be directed to the textbox. You could always try setting the KeyPreview to True on the Form. Then on the KeyPress you could try

              private void YourForm\_KeyPress(object sender, KeyPressEventArgs e)
              {
                  ScannerFirstKeyValue = e.KeyChar.ToString();
          
                  if (this.ActiveControl != this.YourTextBox)
                  {
                      YourTextBox.AppendText(ScannerFirstKeyValue);
                  }
                  this.ActiveControl = YourTextBox;
              }
          

          This would ensure all input is placed in correct textbox. Remember if you have multiple textboxes this will be a problem!! Unless the BC Reader has some sort of prefix that can distinguish it from a keyboard.

          Regards Mick Curley :)

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #10

          doesn't that prevent people from typing anything in any other Control? :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


          I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


          H M 2 Replies Last reply
          0
          • L Luc Pattyn

            doesn't that prevent people from typing anything in any other Control? :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


            I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


            H Offline
            H Offline
            Heinzzy
            wrote on last edited by
            #11

            But we still can distinguish BC from user by using prefixes. What do you think?

            1 Reply Last reply
            0
            • L Luc Pattyn

              doesn't that prevent people from typing anything in any other Control? :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


              I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


              M Offline
              M Offline
              michaelgr1
              wrote on last edited by
              #12

              Hi, I need this thing only to read data from barcode reader. Is there a way so only data from it (COM1 port for example) will be insereted to that textbox or the clipboard even if the application is not in focus (in background)?

              H 1 Reply Last reply
              0
              • M michaelgr1

                Hello, I have a textbox in my window application. I want to be able to write into the textbox even if the application window not in focus (not "first" on the screen). How can i do it? If i need to use events for it , i don't know exacly how to write an event and where to put each code piece (the event handler etc.)

                W Offline
                W Offline
                wjp_auhtm
                wrote on last edited by
                #13

                I think that you need create a windows service. When the computer got data, the service app show the data on the form's textbox, even the form unfocused.

                M R 2 Replies Last reply
                0
                • W wjp_auhtm

                  I think that you need create a windows service. When the computer got data, the service app show the data on the form's textbox, even the form unfocused.

                  M Offline
                  M Offline
                  michaelgr1
                  wrote on last edited by
                  #14

                  OK how can i do it using my application?

                  W 1 Reply Last reply
                  0
                  • M michaelgr1

                    Hi, I need this thing only to read data from barcode reader. Is there a way so only data from it (COM1 port for example) will be insereted to that textbox or the clipboard even if the application is not in focus (in background)?

                    H Offline
                    H Offline
                    Heinzzy
                    wrote on last edited by
                    #15

                    Although it's rather unwieldy task I guess I know a way to perform it. To interact with an application that is not in focus I recommend you to use windows application log. Create the window service to handle BC input and write it down to the Log. In the application - check the Log for new entries on timer event and if it exists put it into your textbox. So despite your application might be not in focuse it still can achieve data from BC.

                    M 1 Reply Last reply
                    0
                    • H Heinzzy

                      Although it's rather unwieldy task I guess I know a way to perform it. To interact with an application that is not in focus I recommend you to use windows application log. Create the window service to handle BC input and write it down to the Log. In the application - check the Log for new entries on timer event and if it exists put it into your textbox. So despite your application might be not in focuse it still can achieve data from BC.

                      M Offline
                      M Offline
                      michaelgr1
                      wrote on last edited by
                      #16

                      i think a better way is to create a windows service that will read the data from the Barcode reader and then put in in the clipboard. But i don't know how to create such service and how to read from this device (USB port)

                      H 1 Reply Last reply
                      0
                      • M michaelgr1

                        Hello, I have a textbox in my window application. I want to be able to write into the textbox even if the application window not in focus (not "first" on the screen). How can i do it? If i need to use events for it , i don't know exacly how to write an event and where to put each code piece (the event handler etc.)

                        H Offline
                        H Offline
                        Heinzzy
                        wrote on last edited by
                        #17

                        To capture Keyboard stream use hooks Read this http://msdn.microsoft.com/en-us/library/ms632589(VS.85).aspx[^] Simple example using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; namespace hook { class Program { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private static LowLevelKeyboardProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; static void Main() { _hookID = SetHook(_proc); Application.Run(); UnhookWindowsHookEx(_hookID); } 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) && (wParam == (IntPtr)WM_KEYDOWN)) { int vkCode = Marshal.ReadInt32(lParam); if (((Keys)vkCode == Keys.LWin) || ((Keys)vkCode == Keys.RWin)) { Console.WriteLine("{0} blocked!", (Keys)vkCode); return (IntPtr)1; } } return CallNextHookEx(_hookID, 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)] 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)]

                        M 1 Reply Last reply
                        0
                        • M michaelgr1

                          i think a better way is to create a windows service that will read the data from the Barcode reader and then put in in the clipboard. But i don't know how to create such service and how to read from this device (USB port)

                          H Offline
                          H Offline
                          Heinzzy
                          wrote on last edited by
                          #18

                          So, we have a result here. To accomplish the mission you should definitly create a service. With hooks! ;)

                          1 Reply Last reply
                          0
                          • H Heinzzy

                            To capture Keyboard stream use hooks Read this http://msdn.microsoft.com/en-us/library/ms632589(VS.85).aspx[^] Simple example using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; namespace hook { class Program { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private static LowLevelKeyboardProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; static void Main() { _hookID = SetHook(_proc); Application.Run(); UnhookWindowsHookEx(_hookID); } 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) && (wParam == (IntPtr)WM_KEYDOWN)) { int vkCode = Marshal.ReadInt32(lParam); if (((Keys)vkCode == Keys.LWin) || ((Keys)vkCode == Keys.RWin)) { Console.WriteLine("{0} blocked!", (Keys)vkCode); return (IntPtr)1; } } return CallNextHookEx(_hookID, 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)] 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)]

                            M Offline
                            M Offline
                            michaelgr1
                            wrote on last edited by
                            #19

                            how do i use this code? where do i put in? in the program.cs ? and is it a windows service?

                            1 Reply Last reply
                            0
                            • W wjp_auhtm

                              I think that you need create a windows service. When the computer got data, the service app show the data on the form's textbox, even the form unfocused.

                              R Offline
                              R Offline
                              Ravi Bhavnani
                              wrote on last edited by
                              #20

                              A Windows service almost never has access to the desktop.  See this[^] article. /ravi

                              My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                              W 1 Reply Last reply
                              0
                              • M michaelgr1

                                OK how can i do it using my application?

                                W Offline
                                W Offline
                                wjp_auhtm
                                wrote on last edited by
                                #21

                                Oh! I try to open a win app from a windows service, but I was failed. I consider that creating a socket connect between the windows service and the win app may be practicable. creating windows service like this. creating socket like this.

                                M H 2 Replies Last reply
                                0
                                • R Ravi Bhavnani

                                  A Windows service almost never has access to the desktop.  See this[^] article. /ravi

                                  My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                  W Offline
                                  W Offline
                                  wjp_auhtm
                                  wrote on last edited by
                                  #22

                                  Yes, it can not instantiation a win form and show it. But I think that the socket could connect the win service and win app.

                                  1 Reply Last reply
                                  0
                                  • W wjp_auhtm

                                    Oh! I try to open a win app from a windows service, but I was failed. I consider that creating a socket connect between the windows service and the win app may be practicable. creating windows service like this. creating socket like this.

                                    M Offline
                                    M Offline
                                    michaelgr1
                                    wrote on last edited by
                                    #23

                                    OK. But i have another question- If i create a windows service to manage the data from the barcode reader (the data will go to clipboard and then set focus to my application), How can i install this windows service on a user computer (without installutil etc.)?

                                    W 1 Reply Last reply
                                    0
                                    • M michaelgr1

                                      OK. But i have another question- If i create a windows service to manage the data from the barcode reader (the data will go to clipboard and then set focus to my application), How can i install this windows service on a user computer (without installutil etc.)?

                                      W Offline
                                      W Offline
                                      wjp_auhtm
                                      wrote on last edited by
                                      #24

                                      You could install the windows service like this, if u are using .Net FrameWork 3.5. I found that the file named "System.Configuration.Install.dll" in .Net 2.0 is different from the .Net 3.5's. There are some simple code.

                                      using System.ServiceProcess;
                                      using System.Configuration.Install;
                                      using System.Collections;

                                              /// <summary>
                                              /// TODO: Is the service is existed and return true or false.
                                              /// </summary>
                                              /// <param name=" NameService ">Name of the windows service.</param>
                                              /// <returns>If the service is existed then return true,or return false.</returns>
                                              private bool isServiceIsExisted(string NameService) 
                                              {
                                                  ServiceController\[\] services = ServiceController.GetServices();
                                                  foreach (ServiceController s in services) 
                                                  {
                                                      if (s.ServiceName.ToLower() == NameService.ToLower()) 
                                                      {
                                                          return true;
                                                      }
                                                  }
                                                  return false;
                                              }
                                      
                                              /// <summary>
                                              /// TODO: Install windows service.
                                              /// </summary>
                                              /// <param name="stateSaver">Collection(default is Null)</param>
                                              /// <param name="filepath">Full path of the windows service file</param>
                                              private void InstallmyService(IDictionary stateSaver, string filepath)
                                              {
                                                  AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
                                                  AssemblyInstaller1.UseNewContext = true;
                                                  AssemblyInstaller1.Path = filepath;
                                                  AssemblyInstaller1.Install(stateSaver);
                                                  AssemblyInstaller1.Commit(stateSaver);
                                                  AssemblyInstaller1.Dispose();
                                              }
                                              /// <summary>
                                              /// TODO: Uninstall windows service.
                                              /// </summary>
                                              /// <param name="filepath">Full path of the windows service file</param>
                                              private void UnInstallmyService(string filepath)
                                              {
                                                  AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
                                                  AssemblyInstaller1.UseNewContext = true;
                                                  AssemblyInstaller1.Path = filepath;
                                                  AssemblyInstaller1.Uninstall(null);
                                                  AssemblyInstaller1.Dispose();
                                              }
                                      

                                      Good Luck!

                                      M 1 Reply Last reply
                                      0
                                      • W wjp_auhtm

                                        You could install the windows service like this, if u are using .Net FrameWork 3.5. I found that the file named "System.Configuration.Install.dll" in .Net 2.0 is different from the .Net 3.5's. There are some simple code.

                                        using System.ServiceProcess;
                                        using System.Configuration.Install;
                                        using System.Collections;

                                                /// <summary>
                                                /// TODO: Is the service is existed and return true or false.
                                                /// </summary>
                                                /// <param name=" NameService ">Name of the windows service.</param>
                                                /// <returns>If the service is existed then return true,or return false.</returns>
                                                private bool isServiceIsExisted(string NameService) 
                                                {
                                                    ServiceController\[\] services = ServiceController.GetServices();
                                                    foreach (ServiceController s in services) 
                                                    {
                                                        if (s.ServiceName.ToLower() == NameService.ToLower()) 
                                                        {
                                                            return true;
                                                        }
                                                    }
                                                    return false;
                                                }
                                        
                                                /// <summary>
                                                /// TODO: Install windows service.
                                                /// </summary>
                                                /// <param name="stateSaver">Collection(default is Null)</param>
                                                /// <param name="filepath">Full path of the windows service file</param>
                                                private void InstallmyService(IDictionary stateSaver, string filepath)
                                                {
                                                    AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
                                                    AssemblyInstaller1.UseNewContext = true;
                                                    AssemblyInstaller1.Path = filepath;
                                                    AssemblyInstaller1.Install(stateSaver);
                                                    AssemblyInstaller1.Commit(stateSaver);
                                                    AssemblyInstaller1.Dispose();
                                                }
                                                /// <summary>
                                                /// TODO: Uninstall windows service.
                                                /// </summary>
                                                /// <param name="filepath">Full path of the windows service file</param>
                                                private void UnInstallmyService(string filepath)
                                                {
                                                    AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
                                                    AssemblyInstaller1.UseNewContext = true;
                                                    AssemblyInstaller1.Path = filepath;
                                                    AssemblyInstaller1.Uninstall(null);
                                                    AssemblyInstaller1.Dispose();
                                                }
                                        

                                        Good Luck!

                                        M Offline
                                        M Offline
                                        michaelgr1
                                        wrote on last edited by
                                        #25

                                        Will this code start the service too?

                                        W 1 Reply Last reply
                                        0
                                        • M michaelgr1

                                          Will this code start the service too?

                                          W Offline
                                          W Offline
                                          wjp_auhtm
                                          wrote on last edited by
                                          #26

                                          If set the windows service autorun, when you restart computer, the service will start. Of course, you can start the service in manual like this.

                                                  /// <summary>
                                                  /// TODO: Start windows service.
                                                  /// </summary>
                                                  /// <param name="name">The name of windows service.</param>
                                                  /// <returns>If success return true,or return false.;</returns>
                                                  private bool StarmyService(string name)
                                                  {
                                                      ServiceController sc = new ServiceController(name);
                                                      if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.StopPending
                                                              )
                                                      {
                                                          sc.Start();
                                                          sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
                                                      }
                                                      else
                                                      {
                                                      }
                                                      sc.Close();
                                                      return true;
                                                  }
                                          

                                          And stop the service like this

                                                  /// <summary>
                                                  /// TODO: Stop windows service.
                                                  /// </summary>
                                                  /// <param name="name">The name of windows service.</param>
                                                  /// <returns>If success return true,or return false.;</returns>
                                                  private bool StopmyService(string name)
                                                  {
                                                      ServiceController sc = new ServiceController(name);
                                                      if (sc.Status == ServiceControllerStatus.Running ||
                                                          sc.Status == ServiceControllerStatus.StartPending)
                                                      {
                                                          sc.Stop();
                                                          sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 10));
                                                      }
                                                      else
                                                      {
                                                      }
                                                      sc.Close();
                                                      return true;
                                                  }
                                          
                                          M 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups