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

时间:2016-10-10 09:10:48

标签: c# windows service mouseevent

我有一个Arduino通过串口通信按钮的状态。在PC上我有一个Windows服务应用程序,它轮询串口以获取按钮的状态。每当我在串口中收到有关按钮状态的消息时,我会将收到的消息写入文件,并且还要记录当前的鼠标位置。在此之后,我想在当前鼠标位置引发左键单击事件。

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

以下是我的C#代码。

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));
        }
    }   
}

我做错了什么?我用Google搜索了几个小时才找到解决方案,但找不到任何相关内容。

0 个答案:

没有答案