⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 service.cs

📁 太阳神短信跟踪服务系统
💻 CS
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Threading;
using System.Runtime.InteropServices;

namespace apolloService
{

	public class Service1 : System.ServiceProcess.ServiceBase
	{
		private System.ComponentModel.IContainer components = null;
		private System.Timers.Timer timer1;
	
		private SqlConnection DB;
		Thread threadForm=null;

		public static string paraConnectionString="server=(local); uid=sa; pwd=; database=apollo";
		public static string paraRunningPeriods="59";

		private string logFilePath="C:\\ApolloLog\\MsgLog" + DateTime.Now.Year.ToString() + Common.NumAdjust(DateTime.Now.Month.ToString()) + Common.NumAdjust(DateTime.Now.Day.ToString()) + ".log" ;

		
		//声明API
		[DllImport("user32.dll")]
		static extern int GetDesktopWindow();

		[DllImport("user32.dll")]
		static extern IntPtr GetProcessWindowStation();

		[DllImport("kernel32.dll")]
		static extern IntPtr GetCurrentThreadId();

		[DllImport("user32.dll")]
		static extern IntPtr GetThreadDesktop(IntPtr dwThread);

		[DllImport("user32.dll")]
		static extern IntPtr OpenWindowStation(string a,bool b,int c);

		[DllImport("user32.dll")]
		static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags,
			bool fInherit, uint dwDesiredAccess);

		[DllImport("user32.dll")]
		static extern IntPtr CloseDesktop(IntPtr p);

		[DllImport("rpcrt4.dll", SetLastError=true)]
		static extern IntPtr RpcImpersonateClient(int i);


		//声明注册快捷键API
		[DllImport("rpcrt4.dll", SetLastError=true)]
		static extern IntPtr RpcRevertToSelf();

		[DllImport("user32.dll")]
		static extern IntPtr SetThreadDesktop(IntPtr a);

		[DllImport("user32.dll")]
		static extern IntPtr SetProcessWindowStation(IntPtr a);
		[DllImport("user32.dll")]
		static extern IntPtr CloseWindowStation(IntPtr a);


		[DllImport("user32.dll", SetLastError=true)] 
		public static extern bool RegisterHotKey(
 			IntPtr hWnd,
 			int id,
 			KeyModifiers fsModifiers,
 			Keys vk);
			
		[DllImport("user32.dll", SetLastError=true)] 
		public static extern bool UnregisterHotKey(
 			IntPtr hWnd,
 			int id);

		[Flags()] 
		public enum KeyModifiers 
		{ 
			None = 0,
 			Alt = 1,
 			Control = 2,
 			Shift = 4,
 			Windows = 8
		}

			
		public Service1()
		{
			// 该调用是 Windows.Forms 组件设计器所必需的。
			InitializeComponent();

			// TODO: 在 InitComponent 调用后添加任何初始化
		}

		// 进程的主入口点
		static void Main()
		{
			System.ServiceProcess.ServiceBase[] ServicesToRun;
	
			// 同一进程中可以运行多个用户服务。若要将
			//另一个服务添加到此进程,请更改下行
			// 以创建另一个服务对象。例如,
			//
			//   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
			//
			ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };

			System.ServiceProcess.ServiceBase.Run(ServicesToRun);

		}

		/// <summary> 
		/// 设计器支持所需的方法 - 不要使用代码编辑器 
		/// 修改此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.timer1 = new System.Timers.Timer();
			((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
			// 
			// timer1
			// 
			this.timer1.Interval = 60000;
			this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
			// 
			// Service1
			// 
			this.ServiceName = "Service";
			((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();

		}

		/// <summary>
		/// 清理所有正在使用的资源。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		/// <summary>
		/// 设置具体的操作,以便服务可以执行它的工作。
		/// </summary>
		protected override void OnStart(string[] args)
		{
			// TODO: 在此处添加代码以启动服务。

			//threadForm=new Thread(new ThreadStart(FormShow));
			//threadForm.Start();
			//Common.writeLog(logFilePath,threadForm.ThreadState.ToString());

			//读短信发送参数
			RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Apollo\\ServicePara");
			try
			{
				paraConnectionString=rk.GetValue("ConnectionString").ToString();
				paraRunningPeriods=rk.GetValue("RunningPeriods").ToString();
				Common.paraStrJLlogName=rk.GetValue("strJLlogName").ToString();
				Common.paraStrJLlogPWD=rk.GetValue("strJLlogPWD").ToString();
			}
			catch(Exception ex)
			{
				Common.writeLog(logFilePath,DateTime.Now.ToString() + "读参数错误!" + ex.Message.ToString());
			}

			timer1.Interval = Int32.Parse(paraRunningPeriods) * 1000;
			//计时器开始计时
			timer1.Start();

			//
			//Common.writeLog(logFilePath,threadForm.Name.ToString());

			//RegisterHotKey(Handle,100,2,System.Windows.Forms.Keys.K);

			//服务开始时写入日志
			Common.writeLog(logFilePath,DateTime.Now.ToString() + " Start apolloService...");
		}
 
		/// <summary>
		/// 停止此服务。
		/// </summary>
		protected override void OnStop()
		{
			// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
			timer1.Stop();

			if(threadForm!=null)
			{
				if(threadForm.IsAlive)
				{
					threadForm.Abort();
					threadForm=null;
				}
			}

			//UnregisterHotKey(Handle,100);

			Common.writeLog(logFilePath,DateTime.Now.ToString() + " Stop apolloService...");
			Common.writeLog(logFilePath,"");
		}

		private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{

			//每天更换新的日志文件
			if(DateTime.Now.Hour==0 && DateTime.Now.Minute==1)
			{
				logFilePath="C:\\ApolloLog\\MsgLog" + DateTime.Now.Year.ToString() + Common.NumAdjust(DateTime.Now.Month.ToString()) + Common.NumAdjust(DateTime.Now.Day.ToString()) + ".log" ;
			}
			//Common.writeLog(logFilePath,DateTime.Now.ToString() );


			DB = new SqlConnection(paraConnectionString);

			//读取当前未发送记录
			SqlDataAdapter sa = new SqlDataAdapter( "select * from TMsg_SendList where SendState<>0 and Sendtime<=getDate() and SendTime>getDate()-0.1",DB );
			DataSet ds = new DataSet();
					
			try
			{
				sa.Fill( ds,"SendTo" );

				if(ds.Tables["SendTo"].Rows.Count>0)
				{
					string strLog="--------------"+ DateTime.Now.ToString() + " start write into log----------------";
					Common.writeLog(logFilePath,strLog);

					DataColumn dc=ds.Tables["SendTo"].Columns["Id"];
					DataColumn[] arrDc=new DataColumn[1];
					arrDc[0]=dc;
					ds.Tables[0].PrimaryKey=arrDc;

					new SqlCommandBuilder(sa);

					for(int i=0;i<ds.Tables[0].Rows.Count;i++)
					{
						DataRow[] dr = ds.Tables["SendTo"].Select("Id=" + ds.Tables["SendTo"].Rows[i]["ID"].ToString());

						//校验手机号
						if(!Common.VerifyMobile(ds.Tables[0].Rows[i]["SendtoMobile"].ToString()))
						{
							Common.writeLog(logFilePath,"SentTo:" + ds.Tables[0].Rows[i]["SendtoMobile"].ToString() + "号码有错误");
							Common.writeLog(logFilePath,"");
							dr[0]["SendState"] = -9;
						}
						else
						{
							//发送短信
							//MessageBox.Show(ds.Tables[0].Rows[i]["SendTo"].ToString());
							int iretState=Common.sendMessage(ds.Tables[0].Rows[i]["SendtoMobile"].ToString(),ds.Tables[0].Rows[i]["SendContent"].ToString());
						
							//修改记录状态
							dr[0]["SendState"] = iretState;

							//写日志
							Common.writeLog(logFilePath,"SendTo:" + ds.Tables[0].Rows[i]["SendtoMobile"].ToString() + ":" + ds.Tables[0].Rows[i]["SendContent"].ToString());
							Common.writeLog(logFilePath,"状态:" + new JL().Message(iretState));
							Common.writeLog(logFilePath,"");
						}
					}

					try
					{
						sa.Update( ds,"SendTo" );
					}
					catch(Exception ex)
					{
						Common.writeLog(logFilePath,"回写数据库失败!" + ex.Message.ToString());
					}
				}
			}
			catch(Exception ex)
			{
				Common.writeLog(logFilePath,DateTime.Now.ToString() + " 读数据库失败:" + ex.Message.ToString());
			}
			DB.Close();
		}

		/// <summary>
		/// 处理快捷键
		/// </summary>
		private void ProcessHotkey()
		{

		}

//		protected override void WndProc(ref Message m)
//		{
//			const int WM_HOTKEY = 0x0312;
//			switch (m.Msg)
//			{
//				case WM_HOTKEY:
//					ProcessHotkey();
//					break;
//			}
//			base.WndProc(ref m);
//		}

		/// <summary>
		/// 显示窗体
		/// </summary>
		private void FormShow()
		{
			GetDesktopWindow();
			IntPtr hwinstaSave = GetProcessWindowStation();
			IntPtr dwThreadId = GetCurrentThreadId();
			IntPtr hdeskSave = GetThreadDesktop(dwThreadId);
			IntPtr hwinstaUser = OpenWindowStation("WinSta0", false,33554432);
			if (hwinstaUser == IntPtr.Zero)
			{
				RpcRevertToSelf();
				return ;
			}
			SetProcessWindowStation(hwinstaUser); 
			IntPtr hdeskUser = OpenDesktop("Default", 0, false, 33554432); 
			RpcRevertToSelf(); 
			if (hdeskUser == IntPtr.Zero) 
			{
				SetProcessWindowStation(hwinstaSave);
				CloseWindowStation(hwinstaUser);
				return;
			} 
			SetThreadDesktop(hdeskUser);

			IntPtr dwGuiThreadId = dwThreadId;

			frmMain f=new frmMain();
			System.Windows.Forms.Application.Run(f);
			
			dwGuiThreadId = IntPtr.Zero;
			SetThreadDesktop(hdeskSave);
			SetProcessWindowStation(hwinstaSave);
			CloseDesktop(hdeskUser);
			CloseWindowStation(hwinstaUser);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -