Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GetCursorPos在Windows服务应用程序中返回0_C#_Windows_Service_Mouseevent - Fatal编程技术网

C# GetCursorPos在Windows服务应用程序中返回0

C# GetCursorPos在Windows服务应用程序中返回0,c#,windows,service,mouseevent,C#,Windows,Service,Mouseevent,我有一个Arduino通过串行端口传送按钮的状态。在PC上,我有一个Windows服务应用程序,它正在轮询串行端口以获取按钮的状态。每当我在串行端口收到关于按钮状态的消息时,我都会将收到的消息写入一个文件,并希望记录当前鼠标位置。接下来,我想在当前鼠标位置引发一个左键单击事件 出于某种原因,当我使用GetCursorPos读取当前鼠标位置时,我总是得到0,0作为鼠标位置。我正在使用user32.dll来执行此操作 下面是我的C代码 我做错了什么?我在谷歌上搜索了几个小时以找到解决方案,但找不到任

我有一个Arduino通过串行端口传送按钮的状态。在PC上,我有一个Windows服务应用程序,它正在轮询串行端口以获取按钮的状态。每当我在串行端口收到关于按钮状态的消息时,我都会将收到的消息写入一个文件,并希望记录当前鼠标位置。接下来,我想在当前鼠标位置引发一个左键单击事件

出于某种原因,当我使用GetCursorPos读取当前鼠标位置时,我总是得到0,0作为鼠标位置。我正在使用user32.dll来执行此操作

下面是我的C代码


我做错了什么?我在谷歌上搜索了几个小时以找到解决方案,但找不到任何相关信息。

您应该了解windows计算机上运行的服务应用程序的限制。可能是不允许服务获取游标的当前位置。我认为您可以在特定用户帐户或整个系统下运行服务。您的服务运行在单独的非交互式窗口站/桌面上,但您试图读取当前用户窗口站/桌面上的鼠标位置,而您不能。处理所需行为的正确方法是让代码在用户会话中运行,并让服务调用它以检索光标位置。@MCND在哪里可以找到有关如何执行您在评论中提到的操作的信息,特别是有关为什么它是一个糟糕的设计的所有警告。然后进入类似的领域。其余部分是应用程序和服务之间的IPC。您应该查看windows计算机上运行的服务应用程序的限制。可能是不允许服务获取游标的当前位置。我认为您可以在特定用户帐户或整个系统下运行服务。您的服务运行在单独的非交互式窗口站/桌面上,但您试图读取当前用户窗口站/桌面上的鼠标位置,而您不能。处理所需行为的正确方法是让代码在用户会话中运行,并让服务调用它以检索光标位置。@MCND在哪里可以找到有关如何执行您在评论中提到的操作的信息,特别是有关为什么它是一个糟糕的设计的所有警告。然后进入类似的领域。其余部分是应用程序和服务之间的IPC。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace MouseInterface
{
    public class MyMouseClass
    {
        [DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004
        }

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(ref Point pt);

        public static void LeftDown(int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event((int)(MouseEventFlags.LEFTDOWN), x, y, 0, 0);
        }

        public static void LeftUp(int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event((int)(MouseEventFlags.LEFTUP), x, y, 0, 0);
        }
    }

    public partial class Service1 : ServiceBase
    {
        private HCIDevice hcidev;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            hcidev = new HCIDevice();
            hcidev.init();
        }

        protected override void OnStop()
        {
            hcidev.terminate();
        }

        private void onElapsedTimer(object source, ElapsedEventArgs e)
        {

        }
    }


    public class HCIDevice
    {
        private SerialPort _sPort;
        private Thread _reader;
        private bool _connected;
        private bool _stop;
        private System.Timers.Timer _contimer = new System.Timers.Timer();

        public HCIDevice()
        {
            // create a new serial port
            _sPort = new SerialPort();
            // update settings
            updateSerialPortSettings();

            // set reader and writer threads.
            _reader = new Thread(this._readerthread);

            // reset flags.
            _connected = false;
            _stop = false;

            // start the thread.
            //init();
        }

        public void connect()
        {
            if (this._sPort.IsOpen == false)
            {
                try
                {
                    this._sPort.Open();
                    _connected = true;
                    AddToFile("Device connected!\n");
                }
                catch
                {
                }
            }
        }

        public void disconnect()
        {
            if (this._sPort.IsOpen)
            {
                this._sPort.Close();
            }
            _connected = false;
            AddToFile("Device disconnected!\n");
        }

        public void init()
        {
            try
            {
                this._stop = false;
                // start thread.
                this._reader.Start();
            }
            catch
            {
                //AddToFile("Service could not be started!\n");
            }
        }

        public void terminate()
        {
            // first stop.
            this._stop = true;
            this._reader.Join();
            //AddToFile("Device stopped!");
        }

        public bool isRunning()
        {
            return (this._stop == false);
        }

        public bool isConnected()
        {
            return this._sPort.IsOpen;
        }

        private void updateSerialPortSettings()
        {
            // Allow the user to set the appropriate properties.
            this._sPort.PortName = System.Configuration.ConfigurationManager.AppSettings["devCOM"];
            this._sPort.BaudRate = int.Parse(System.Configuration.ConfigurationManager.AppSettings["devbaudrate"]);
            this._sPort.Parity = Parity.None;
            this._sPort.DataBits = 8;
            this._sPort.StopBits = StopBits.One;
            this._sPort.Handshake = Handshake.None;

            // Set the read/write timeouts
            this._sPort.ReadTimeout = 500;
            this._sPort.WriteTimeout = 500;
        }

        private void _readerthread()
        {
            byte[] _rxdata = new byte[1024];
            //int n;
            double nanosecPerTick = 1.0 / Stopwatch.Frequency;
            Stopwatch stp_watch = new Stopwatch();
            stp_watch.Start();

            AddToFile("Service started!\n");
            while (_stop == false)
            {
                // make sure the device is still connected.
                if (isConnected())
                {

                    // Do nothing if in pause
                   // Not paused read data and parse
                    try
                    {
                        handle_message();
                    }
                    catch (System.TimeoutException) { }
                }
                else
                {
                    // Just got disconnected?
                    if (_connected)
                    {
                        disconnect();
                        // Reset timer.
                        stp_watch.Reset();
                        stp_watch.Start();
                    }
                    else
                    {
                        // try to connect every one second.
                        if (stp_watch.ElapsedMilliseconds >= 1000)
                        {
                            connect();
                            // Reset timer.
                            stp_watch.Reset();
                            if (_connected == false)
                            {
                                stp_watch.Start();
                            }
                        }
                    }
                }
            }
            disconnect();
            AddToFile("Service stopped!\n");
        }

        private void AddToFile(string line)
        {
            using (FileStream fs = File.Open(System.Configuration.ConfigurationManager.AppSettings["logloc"], FileMode.Append, FileAccess.Write, FileShare.None))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(string.Format("{0} {1}", DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss"), line));
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        private void handle_message()
        {
            // read line.
            string msg = _sPort.ReadLine();
            AddToFile(msg);
            Point pt = new Point();
            MyMouseClass.GetCursorPos(ref pt);
            AddToFile(string.Format("{0}, {1}", pt.X, pt.Y));
        }
    }   
}