0

After doing some searching, I've come to understand that when creating a windows service application, you can implement STA threads to access the clipboard as follows:

thread th  = new thread(myMethod);
th.SetApartmentState(ApartmentState.STA);
th.Start();

Under the myMethod call:

Clipboard.SetText("TEST");

At first glance, this appears to not be working. However, after running through some tests, I've since learned that STA threads can access the clipboard, which is separate from the Windows clipboard.

ie. I can SetText and GetText in this STA clipboard, but I can't do a copy/paste from windows (Control+C, Control+X, Control+V).

Please advise, how can I access the actual windows clipboard from STA so that I can Control+V the set content?

chris
  • 1
  • The clipboard is associated with a desktop. A desktop is associated with a session. A service runs in a distinct session, there is nobody around in that same session to paste that text. Google "session 0 isolation" to learn why this can't work. – Hans Passant Oct 18 '18 at 21:52

1 Answers1

0

I will tell you my experiences on working with windows services. It may help you to do your work.

  1. Windows Service Applications are run as LocalSystem, NetworkService and LocalService Users and they are not depended on any specific user (Normal Users). These are System Users.

  2. System Users has it own Session. Session is a Collection of the paths (My documents, AppData, ...), User Desktop GUI, Settings (Any application Settings and User Preferences), EnvironmentVariables and Clipboard (I'm Not sure about the Clipboard but it is absolutely logical) So you may want to find a way to get the Session of any logged in Users (This is a practical way and i have done that before it's called Impersonation and it's about getting an logged in user's token and ....).

  3. Before solving your windows service problems, check them in a User Session using this pattern:

3-1.Add this method into WindowsService1 class:

 public void OnDebug()
 {
    OnStart(null);
 }

3-2.In Program.cs file change the content to something like it:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
      #if DEBUG
        var Service = new WindowsService1();
        Service.OnDebug();
      #else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new WindowsService1()
        };
        ServiceBase.Run(ServicesToRun);
      #endif
    }
}

By this way you can run your code in User Session and check possible problems (Non User-Specific Problems).

After Checking you codes in above pattern you may see that your code is working or not. and this is the way you will find that you must change your codes or user Session.

RezaNoei
  • 1,266
  • 1
  • 8
  • 24