?? service.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 + -