Files
lserp_cs_5.0/插件库/CommonLib/utils/PubUtil.cs
T
2026-07-10 15:25:05 +08:00

602 lines
23 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Data;
using CommonLib.utils;
using System.Diagnostics;
namespace CommonLib {
public abstract class PubUtil {
public static Dictionary<string, DllModule> ModuleForms = new Dictionary<string, DllModule>();
//-----------------------------------------------------调用delphi或者c#库函数-------------------------------------------------------------//
//[DllImport("lib/DelphiDll.dll")]
//private static extern void Delphi_Show();
[DllImport("user32.dll", EntryPoint = "SetParent")]
public static extern IntPtr SetParent(IntPtr hChild, IntPtr hParent);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);
//调用delphi库函数
[DllImport("lib/DelphiDll.dll")]
public static extern int Delphi_Call(StringBuilder Path, StringBuilder Path1, StringBuilder FrmCaption,
StringBuilder SysParameterStr1, StringBuilder SysParameterStr2, int FrmShowid, StringBuilder SysParameterStr3);
////调用delphi库函数
//[DllImport("lib/DelphiDll.dll")]
//private static extern StringBuilder Delphi_CallEx(StringBuilder Path, StringBuilder Path1, StringBuilder FrmCaption,
// StringBuilder SysParameterStr1, StringBuilder SysParameterStr2, int FrmShowid, StringBuilder SysParameterStr3);
//设置delphi连接数据库函数
[DllImport("lib/DelphiDll.dll")]//, EntryPoint="Delphi_Init" CharSet=Charset.Ansi]
public static extern int Delphi_Init(StringBuilder ConStr);
//设置delphi库调用参数
[DllImport("lib/DelphiDll.dll")]
public static extern int Delphi_SetParams(int OperatorID, int systemID, StringBuilder OperatorName, StringBuilder WSName, StringBuilder SkinPathStr);
//给调用delphi库的通用库设置主窗体句柄 CallingConvention = CallingConvention.StdCall)
[DllImport("lib/DelphiDll.dll")]
public static extern int SetMainHandle(int MainHandle);
//delphi调用c#库
[DllImport("lib/DelphiDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int DelphiCallCSharpDll(StringBuilder DLLName, StringBuilder parms);
//获取两个密码
[DllImport("lib/DelphiDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool GetValidateCode(ref StringBuilder ValidateCodeE, ref int CodeELen, ref StringBuilder ValidateCodeT, ref int CodeTLen);
//调用delphi库函数
[DllImport("lib/DelphiDll.dll")]
public static extern int FreeDll(StringBuilder libKey);
////调用delphi库函数
//[DllImport("lib/DelphiDll.dll")]
//public static extern int Delphi_UnInit();
//调用delphi库函数下载附件
[DllImport("lib/DelphiDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern StringBuilder DownloadAttach(StringBuilder dfile, int hwnd);
/// <summary>
/// c#库标准调用模式
/// </summary>
/// <param name="DllFileName"></param>
/// <param name="args"></param>
public static void LoadDll(string DllFileName, string[] args) {
Cursor.Current = Cursors.WaitCursor;
try {
Assembly _Assembly = Assembly.LoadFrom(AbsolutelyPath + "lib/" + DllFileName);
Type[] _types = _Assembly.GetTypes();
foreach (Type _type in _types) {
if (_type.ToString().EndsWith(".DllBaseClass") == false)
continue;
//根据类型创建一个类并将参数通过构造函数传入
object[] ol = new object[] { args };
object _DllInstance = Activator.CreateInstance(_type, ol);
}
_Assembly = null;
}
catch (Exception ex) {
PubUtil.WriteError("调用C#库出错!", ex.Message);
MessageBox.Show("调用C#库出错!" + ex.Message);
}
finally {
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// c#库标准调用模式
/// </summary>
/// <param name="DllFileName"></param>
/// <param name="args"></param>
public static IForm LoadDllForm(string DllFileName, string[] args) {
IForm form = null;
Cursor.Current = Cursors.WaitCursor;
try {
//if ("lskj.pubbrower.dll" == DllFileName.ToLower()) DllFileName = "chrome/" + DllFileName;
Assembly _Assembly = Assembly.LoadFrom(AbsolutelyPath + "lib/" + DllFileName);
Type[] _types = _Assembly.GetTypes();
foreach (Type _type in _types) {
if (_type.ToString().EndsWith(".DllBaseClass") == false)
continue;
object[] ol = new object[] { args };
//根据类型创建一个类并将参数通过构造函数传入
form = Activator.CreateInstance(_type, ol) as IForm;
}
_Assembly = null;
}
catch (Exception ex) {
PubUtil.WriteError("调用C#库出错1", ex.Message);
MessageBox.Show("调用C#库出错1" + ex.Message);
}
finally {
Cursor.Current = Cursors.Default;
}
return form;
}
/// <summary>
/// c#库标准调用模式
/// </summary>
/// <param name="DllFileName"></param>
/// <param name="args"></param>
public static IForm LoadDllForm2(string DllFileName, string[] args) {
IForm form = null;
Cursor.Current = Cursors.WaitCursor;
try {
Assembly _Assembly = Assembly.LoadFrom(AbsolutelyPath + DllFileName);
Type[] _types = _Assembly.GetTypes();
foreach (Type _type in _types) {
if (_type.ToString().EndsWith(".DllBaseClass") == false)
continue;
object[] ol = new object[] { args };
//根据类型创建一个类并将参数通过构造函数传入
form = Activator.CreateInstance(_type, ol) as IForm;
}
_Assembly = null;
}
catch (Exception ex) {
PubUtil.WriteError("调用C#库出错2", ex.Message);
MessageBox.Show("调用C#库出错2" + ex.Message);
}
finally {
Cursor.Current = Cursors.Default;
}
return form;
}
/// <summary>
/// 调用delphi库或者c#库
/// </summary>
/// <param name="DllFileName">库名</param>
/// <param name="NewModelFlag">有值表示调用c#库</param>
public static void LoadDllEx(string DllFileName, string NewModelFlag) {
if (NewModelFlag == "")//调用delphi库
{
/*
string Path = "E:/ERP3.0/pub/lib/wms_BillCpJoinRp.lsp";
string Path1 = "wms_BillCpJoinRp.lsp";
string FrmCaption = "";
string SysParameterStr1 = "";
//SysParameterStr1.Append("1101");
string SysParameterStr2 = "";
//SysParameterStr2.Append("1801");
string SysParameterStr3 = "";
//SysParameterStr3.Append("RK13090079");
Delphi_Call_Ready(Path, Path1, FrmCaption, SysParameterStr1, SysParameterStr2, 0, SysParameterStr3);
*/
LoadDelphiDll(DllFileName);
}
else//调用C#库
{
LoadDll(DllFileName, new string[] { });
}
}
/// <summary>
/// 调用delphi库
/// </summary>
/// <param name="DllFileName">库名</param>
public static int LoadDelphiDll(string DllFileName) {
return LoadDelphiDll("lib/" + DllFileName, DllFileName, "", "", "", 0, "");
}
//调用delphi库
public static int LoadDelphiDll(string sPath, string sPath1) {
return LoadDelphiDll(sPath, sPath1, "", "", "", 0, "");
}
//调用delphi库
public static int LoadDelphiDll(string sPath, string sPath1, string sFrmCaption) {
return LoadDelphiDll(sPath, sPath1, sFrmCaption, "", "", 0, "");
}
//调用delphi库
public static int LoadDelphiDll(string sPath, string sPath1, string sFrmCaption,
string sSysParameterStr1, string sSysParameterStr2, int FrmShowid, string sSysParameterStr3) {
int Result = 0;
Cursor.Current = Cursors.WaitCursor;
try {
StringBuilder Path = new StringBuilder();
Path.Append(sPath);
StringBuilder Path1 = new StringBuilder();
Path1.Append(sPath1);
StringBuilder FrmCaption = new StringBuilder();
FrmCaption.Append(sFrmCaption);
StringBuilder SysParameterStr1 = new StringBuilder();
SysParameterStr1.Append(sSysParameterStr1);
StringBuilder SysParameterStr2 = new StringBuilder();
SysParameterStr2.Append(sSysParameterStr2);
StringBuilder SysParameterStr3 = new StringBuilder();
SysParameterStr3.Append(sSysParameterStr3);
//Delphi_Show();
Result = Delphi_Call(Path, Path1, FrmCaption, SysParameterStr1, SysParameterStr2, FrmShowid, SysParameterStr3);
}
catch (Exception ex) {
PubUtil.WriteError("调用delphi库出错!", ex.Message);
MessageBox.Show("调用delphi库出错!");
}
finally {
Cursor.Current = Cursors.Default;
}
return Result;
}
///// <summary>
///// 调用delphi库
///// </summary>
///// <param name="DllFileName">库名</param>
//public static StringBuilder LoadDelphiDllEx(string DllFileName)
//{
// return LoadDelphiDllEx("lib/" + DllFileName, DllFileName, "", "", "", 0, "");
//}
////调用delphi库
//public static StringBuilder LoadDelphiDllEx(string sPath, string sPath1, string sFrmCaption,
// string sSysParameterStr1, string sSysParameterStr2, int FrmShowid, string sSysParameterStr3)
//{
// StringBuilder Result = new StringBuilder();
// Cursor.Current = Cursors.WaitCursor;
// try
// {
// StringBuilder Path = new StringBuilder();
// Path.Append(sPath);
// StringBuilder Path1 = new StringBuilder();
// Path1.Append(sPath1);
// StringBuilder FrmCaption = new StringBuilder();
// FrmCaption.Append(sFrmCaption);
// StringBuilder SysParameterStr1 = new StringBuilder();
// SysParameterStr1.Append(sSysParameterStr1);
// StringBuilder SysParameterStr2 = new StringBuilder();
// SysParameterStr2.Append(sSysParameterStr2);
// StringBuilder SysParameterStr3 = new StringBuilder();
// SysParameterStr3.Append(sSysParameterStr3);
// //Delphi_Show();
// Result = Delphi_CallEx(Path, Path1, FrmCaption, SysParameterStr1, SysParameterStr2, FrmShowid, SysParameterStr3);
// }
// catch (Exception ex)
// {
// PubUtil.WriteError("调用delphi库出错!", ex.Message);
// MessageBox.Show("调用delphi库出错!");
// }
// finally
// {
// Cursor.Current = Cursors.Default;
// }
// return Result;
//}
//------------------------------------------------------------------------------------------------------------------//
public const int WM_USER = 0x400;
/// <summary>
/// 密码加密
/// </summary>
/// <param name="strPassword"></param>
/// <returns></returns>
public static string EncryptPassword(string strPassword) {
strPassword = "2006" + strPassword + "New System";
byte[] bytePassword = System.Text.Encoding.ASCII.GetBytes(strPassword);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] dataHashed = sha.ComputeHash(bytePassword);
string hash = BitConverter.ToString(dataHashed).Replace("-", "");
return hash;
}
/// <summary>
/// 关闭释放传入的窗体
/// </summary>
/// <param name="FrmSource"></param>
public static void ReleaseForm(Form FrmSource) {
if (FrmSource != null) {
FrmSource.Close();
FrmSource.Dispose();
}
FrmSource = null;
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="str"></param>
public static void WriteLog(string str) {
try {
string fileName = AbsolutelyPath + "clientLogs/" + DateTime.Now.ToString("yyyy-MM-dd") + "记录.txt";
StreamWriter sr;
if (File.Exists(fileName))
sr = File.AppendText(fileName);
else
sr = File.CreateText(fileName);
sr.WriteLine(DateTime.Now.ToString("HH:mm:ss:fff") + str);
//sr.WriteLine("\n");
sr.Close();
}
catch (Exception) {
}
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="sFormat"></param>
/// <param name="args"></param>
public static void WriteLog(string sFormat, params object[] args) {
WriteLog(string.Format(sFormat, args));
}
/// <summary>
/// 写错误日志
/// </summary>
/// <param name="Content">错误描述</param>
/// <param name="ErrMsg">错误详细信息</param>
public static void WriteError(string Content, string ErrMsg) {
try {
string strSql = string.Format("insert into p_errlogtab(Operatedate,Operator,Content,ErrMsg,Ws) values(getdate(),'{0}',@Content,@ErrMsg,'{1}')",
ERPInfo.Instance.EmployeeName, ERPInfo.Instance.WSName);
SqlParameter[] cmdParams = new SqlParameter[] {
new SqlParameter("@Content",SqlDbType.VarChar,500),
new SqlParameter("@ErrMsg",SqlDbType.VarChar,8000)};
cmdParams[0].Value = Content;
cmdParams[1].Value = ErrMsg;
SqlHelper.ExecuteNonQuery(CommandType.Text, strSql, cmdParams);
if (true)
WriteLog(Content + " " + ErrMsg);
}
catch (Exception ex) {
WriteLog(ex.Message);
}
}
/// <summary>
/// 检查主界面显示方式(1.传统显示)
/// </summary>
/// <returns></returns>
public static int DefaultMainTag()
{
int tag = 1;
try
{
string sqlValue = "select defaultMainTag from p_SystemTab";
string tagValue = SqlHelper.ExecuteDataTable(sqlValue).Rows[0]["defaultMainTag"] + "";
if (!string.IsNullOrEmpty(tagValue))
{
tag = Convert.ToInt32(tagValue);
}
}
catch (Exception ex)
{
}
return tag;
}
/// <summary>
/// 拷贝数据消息值
/// </summary>
public const int WM_COPYDATA = 0x004A;
/// <summary>
/// 关闭窗体消息值
/// </summary>
public const int WM_CLOSE = 0x0010;
/// <summary>
/// 写模块操作日志("唯一字符串",p_formmenuconfigtab表的MenuId,"操作模块"p_formmenuconfigtab表的MenuCaptionp_formmenuconfigtab表的MenuCaption)
/// </summary>
/// <param name="Systmp"></param>
/// <param name="Code"></param>
/// <param name="OperatType"></param>
/// <param name="OperatContent"></param>
/// <param name="OperatObject"></param>
public static void WriteOpLog(string Systmp, string Code, string OperatType, string OperatContent, string OperatObject) {
try {
string strSql = string.Format(@"insert into P_LogTab(Coid,systemtmp,Type,Content,Object,stdt,Operator,Ws) values('{0}','{1}','{2}','{3}','{4}',getdate(),'{5}','{6}')",
Code, Systmp, OperatType, OperatContent, OperatObject, ERPInfo.Instance.EmployeeName, GetMachineName());
SqlHelper.ExecuteNonQuery(CommandType.Text, strSql, null);
}
catch (Exception ex) {
WriteError("日志记录出错错误", ex.Message);
}
}
/// <summary>
/// 登出模块记录
/// </summary>
/// <param name="Systmp"></param>
public static void WriteOpLog(string Systmp) {
try {
string strSql = string.Format("update P_LogTab set eddt=getdate() where systemtmp='{0}'", Systmp);
SqlHelper.ExecuteNonQuery(CommandType.Text, strSql, null);
}
catch (Exception ex) {
WriteError("日志记录出错错误", ex.Message);
}
}
//window api 查找指定窗体名称或者类名的窗体
[DllImport("User32.dll ", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
//获取计算机名称
public static string GetMachineName() {
return Dns.GetHostName();
//IPHostEntry iplist = Dns.GetHostByAddress("127.0.0.1");
//return iplist.HostName;
//IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
}
//window api 运行一个指定程序
[DllImport("kernel32.dll")]
public static extern int WinExec(string exeName, int operType);
//window api 发消息
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
//返回当前系统绝对路径
public static string AbsolutelyFileName {
get { return System.Windows.Forms.Application.ExecutablePath; }
}
//返回当前系统相对路径
public static string AbsolutelyPath {
get
{
try
{
if (string.IsNullOrEmpty(DBConfig.Instance.ProgramPath))
{
DBConfig.Instance.ReadConfig();
}
}
catch (Exception)
{
}
if (!string.IsNullOrEmpty(DBConfig.Instance.ProgramPath))
{
return DBConfig.Instance.ProgramPath + "/";
}
else
{
return Application.StartupPath + "/";
}
}
}
//返回当前打印模板位置
/// <summary>
/// 打印模板 repx文件存放地址
/// </summary>
public static string PrintModePath
{
get
{
string filePath = AbsolutelyPath + "/Reports/";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
return filePath;
}
}
//返回通讯系统程序所在的绝对路径
public static string LSTestFileName {
get { return AbsolutelyPath + "LSTest.exe"; }
}
public static string getHostName() {
String hostName = string.Empty;
try {
hostName = Dns.GetHostName();
}
catch {
}
return hostName;
}
#region 卸载DLL模块、释放内存资源
/// <summary>
/// 卸载DLL模块、释放内存资源
/// </summary>
/// <param name="form"></param>
public static void UnLoadDLL(Form form) {
if (form != null) {
form.Close();
form.Dispose();
form = null;
ClearMemory();
}
}
#endregion
#region 释放内存资源
/// <summary>
/// 释放内存资源
/// </summary>
/// <param name="process"></param>
/// <param name="minSize"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 释放内存
/// </summary>
public static void ClearMemory() {
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
#endregion
#region 调用windows程序
public static bool StartProcess(string filename, string[] args)
{
try
{
string s = "";
foreach (string arg in args)
{
s = s + arg + " ";
}
s = s.Trim();
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(filename, s);
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.Start();
return true;
}
catch (Exception ex)
{
MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
}
return false;
}
#endregion
}
}