示例#1
0
        protected override void SetVisibleCore(bool value)
        {
            // Prevent window getting visible
            if (mInstance == null)
            {
                try
                {
                    if (!this.IsHandleCreated)
                    {
                        CreateHandle();
                    }
                }
                catch (Exception ex)
                {
                    TmoShare.WriteLog(ex.Message);
                }
                mInstance = this;
            }

            base.SetVisibleCore(false);
            if (DeviceAttached != null)
            {
                DeviceAttached(null);                           //首次运行 扫描已经插入设备
            }
        }
示例#2
0
        private void ReadCompleted(IAsyncResult iResult)
        {
            // Retrieve the stream and read buffer.
            var syncObj = (SyncObjT)iResult.AsyncState;

            try
            {
                // call end read : this throws any exceptions that happened during the read
                syncObj.Fs.EndRead(iResult);
                try
                {
                    if (DataReceived != null)
                    {
                        DataReceived(syncObj.Buf);
                    }
                }
                finally
                {
                    // when all that is done, kick off another read for the next report
                    BeginAsyncRead(ref syncObj.Fs, syncObj.Buf.Length);
                }
            }
            catch (IOException ex)      // if we got an IO exception, the device was removed
            {
                TmoShare.WriteLog(ex.ToString());
            }
        }
示例#3
0
        public void HandleDeviceNotificationMessages(Message m)
        {
            // Make sure this is a device notification
            if (m.Msg != Constants.WmDevicechange)
            {
                return;
            }
            try
            {
                switch (m.WParam.ToInt32())
                {
                // Device attached
                case Constants.DbtDevicearrival:
                    TmoShare.WriteLog("handleDeviceNotificationMessages() -> 新设备插入");
                    // If our target device is not currently attached, this could be our device, so we attempt to find it.
                    ReportDeviceAttached(m);
                    break;

                // Device removed
                case Constants.DbtDeviceremovecomplete:
                    TmoShare.WriteLog("handleDeviceNotificationMessages() -> 设备拔出");
                    ReportDeviceDetached(m);
                    break;

                // Other message
                default:
                    TmoShare.WriteLog("handleDeviceNotificationMessages() -> 未知设备事件");
                    break;
                }
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("handleDeviceNotificationMessages() -> 发生异常:" + ex.Message);
            }
        }
示例#4
0
        public bool WriteBSToDevice(byte[] writeBS)
        {
            if (!_deviceInformation.IsDeviceAttached)
            {
                TmoShare.WriteLog(":WriteBSToDevice(): -> 发送失败-设备未连接!");
                return(false);
            }

            try
            {
                lock (writeBSLock)
                {
                    int sendCount = (int)Math.Ceiling(writeBS.Length / 8.0);
                    USBQHIDDLL.SetDeviceHandle(_deviceInformation.HidHandle);
                    //int n = USBQHIDDLL.BFindUsb();
                    //TmoShare.WriteLog("找到设备:" + n);
                    for (int i = 0; i < sendCount; i++)
                    {
                        int    surplusCount = writeBS.Length - i * 8;
                        byte[] send         = new byte[surplusCount >= 8 ? 8 : surplusCount];
                        Array.Copy(writeBS, 8 * i, send, 0, send.Length);
                        if (!USBQHIDDLL.BWrite(send))
                        {
                            return(false);
                        }
                    }
                    //Thread.Sleep(50);
                    //USBQHIDDLL.SetDeviceHandle(_deviceInformation.ReadHandle);
                    byte[] tmp       = new byte[9];
                    int    readCount = writeBS[1] == 0x03 ? 98 : 2;
                    byte[] data      = new byte[readCount * 8];
                    for (int i = 0; i < readCount; i++)
                    {
                        USBQHIDDLL.BRead(tmp);
                        Array.Copy(tmp, 1, data, i * 8, 8);
                    }
                    for (int j = 0; j < data.Length; j++)
                    {
                        TmoShare.WriteLog("收到字节:" + data[j]);
                    }
                    if (DataReceived != null)
                    {
                        DataReceived(data);
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("DeviceCommunication:WriteBSToDevice(): -> 发生异常: " + ex.Message);
                return(false);
            }
        }
示例#5
0
        private void BeginAsyncRead(ref FileStream fs, int iBufLen)
        {
            var syncObj = new SyncObjT {
                Fs = fs, Buf = new Byte[iBufLen]
            };

            try
            {
                fs.BeginRead(syncObj.Buf, 0, iBufLen, ReadCompleted, syncObj);
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog(ex.Message);
            }
        }
示例#6
0
 public static void Stop()
 {
     try
     {
         if (mInstance == null)
         {
             throw new InvalidOperationException("还未启动监测");
         }
         if (th != null && th.ThreadState != System.Threading.ThreadState.Stopped)
         {
             th.Abort();
         }
         mInstance.CrossThreadCalls(() => { mInstance.EndForm(); });
     }
     catch (Exception ex)
     {
         TmoShare.WriteLog(ex.Message);
     }
     mInstance = null;
     th        = null;
 }
示例#7
0
        private string GetDeviceName(Message m)
        {
            try
            {
                if (m.LParam == IntPtr.Zero)
                {
                    return(null);
                }
                var devBroadcastDeviceInterface = new DevBroadcastDeviceinterface1();
                var devBroadcastHeader          = new DevBroadcastHdr();

                try
                {
                    Marshal.PtrToStructure(m.LParam, devBroadcastHeader);
                }
                catch (Exception ex)
                {
                    TmoShare.WriteLog(ex.Message);
                }


                // Is the notification event concerning a device interface?
                if ((devBroadcastHeader.dbch_devicetype == Constants.DbtDevtypDeviceinterface))
                {
                    // Get the device path name of the affected device
                    var stringSize = Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);
                    devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];
                    Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
                    var deviceNameString = new string(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);
                    return(deviceNameString);
                    // Compare the device name with our target device's pathname (strings are moved to lower case
                    //return (string.Compare(deviceNameString.ToLower(), devicepath.ToLower(), StringComparison.OrdinalIgnoreCase) == 0);
                }
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("GetDeviceName(Message m) -> 发生异常:" + ex.Message);
            }
            return(null);
        }
示例#8
0
        public void Disconnect()
        {
            TmoShare.WriteLog("UsbHidDevice:Disconnect() -> 开始释放资源");

            if (_fsDeviceRead != null)
            {
                _fsDeviceRead.Close();
            }
            //if (readDataTh != null)
            //    readDataTh.Abort();
            // Is a device currently attached?
            //if (IsDeviceConnected)
            {
                TmoShare.WriteLog("UsbHidDevice:Disconnect() -> 释放句柄");
                // Close the readHandle, writeHandle and hidHandle
                try
                {
                    if (_deviceInformation.HidHandle != null && !_deviceInformation.HidHandle.IsInvalid())
                    {
                        _deviceInformation.HidHandle.Close();
                    }
                    _deviceInformation.HidHandle = IntPtr.Zero;
                    if (_deviceInformation.ReadHandle != null && !_deviceInformation.ReadHandle.IsInvalid())
                    {
                        _deviceInformation.ReadHandle.Close();
                    }
                    _deviceInformation.ReadHandle = IntPtr.Zero;
                    if (_deviceInformation.WriteHandle != null && !_deviceInformation.WriteHandle.IsInvalid())
                    {
                        _deviceInformation.WriteHandle.Close();
                    }
                    _deviceInformation.WriteHandle = IntPtr.Zero;
                }
                catch { }

                // Set the device status to detached;
                _deviceInformation.IsDeviceAttached = false;
            }
        }
示例#9
0
        public static void QueryDeviceCapabilities(ref DeviceInformationStructure deviceInformation)
        {
            var preparsedData = new IntPtr();

            try
            {
                // Get the preparsed data from the HID driver
                Hid.HidD_GetPreparsedData(deviceInformation.HidHandle, ref preparsedData);

                // Get the HID device's capabilities
                var result = Hid.HidP_GetCaps(preparsedData, ref deviceInformation.Capabilities);
                if ((result == 0))
                {
                    return;
                }

                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() -> 设备信息:");
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Usage: " + Convert.ToString(deviceInformation.Capabilities.Usage + 16));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Usage Page: " +
                                  Convert.ToString(deviceInformation.Capabilities.UsagePage + 16));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Input Report Byte Length: " +
                                  deviceInformation.Capabilities.InputReportByteLength.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Output Report Byte Length: " +
                                  deviceInformation.Capabilities.OutputReportByteLength.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Feature Report Byte Length: " +
                                  deviceInformation.Capabilities.FeatureReportByteLength.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Link Collection Nodes: " +
                                  deviceInformation.Capabilities.NumberLinkCollectionNodes.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Input Button Caps: " +
                                  deviceInformation.Capabilities.NumberInputButtonCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Input Value Caps: " +
                                  deviceInformation.Capabilities.NumberInputValueCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Input Data Indices: " +
                                  deviceInformation.Capabilities.NumberInputDataIndices.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Output Button Caps: " +
                                  deviceInformation.Capabilities.NumberOutputButtonCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Output Value Caps: " +
                                  deviceInformation.Capabilities.NumberOutputValueCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Output Data Indices: " +
                                  deviceInformation.Capabilities.NumberOutputDataIndices.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Feature Button Caps: " +
                                  deviceInformation.Capabilities.NumberFeatureButtonCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Feature Value Caps: " +
                                  deviceInformation.Capabilities.NumberFeatureValueCaps.ToString(CultureInfo.InvariantCulture));
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() ->     Number of Feature Data Indices: " +
                                  deviceInformation.Capabilities.NumberFeatureDataIndices.ToString(CultureInfo.InvariantCulture));
            }
            catch (Exception)
            {
                // Something went badly wrong... this shouldn't happen, so we throw an exception
                TmoShare.WriteLog("DeviceDiscovery:queryDeviceCapabilities() -> EXECEPTION: An unrecoverable error has occurred!");
                throw;
            }
            finally
            {
                // Free up the memory before finishing
                if (preparsedData != IntPtr.Zero)
                {
                    Hid.HidD_FreePreparsedData(preparsedData);
                }
            }
        }
示例#10
0
        public static bool FindTargetDevice(ref DeviceInformationStructure deviceInformation, bool callOther = true)
        {
            TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 开始扫描设备");

            var listOfDevicePathNames = new String[128]; // 128 is the maximum number of USB devices allowed on a single host
            var numberOfDevicesFound  = 0;

            try
            {
                // Reset the device detection flag
                var isDeviceDetected = false;
                deviceInformation.IsDeviceAttached = false;

                // Get all the devices with the correct HID GUID
                bool deviceFoundByGuid = FindHidDevices(ref listOfDevicePathNames, ref numberOfDevicesFound);

                if (deviceFoundByGuid)
                {
                    TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 找到一堆设备");
                    var listIndex = 0;
                    do
                    {
                        TmoShare.WriteLog(string.Format("DeviceDiscovery:findTargetDevice() ->遍历第{0}个设备", listIndex + 1));
                        deviceInformation.HidHandle = Kernel32.CreateFile(listOfDevicePathNames[listIndex], 0, Constants.FileShareRead | Constants.FileShareWrite, IntPtr.Zero, Constants.OpenExisting, 0, 0);

                        if (!deviceInformation.HidHandle.IsInvalid())
                        {
                            deviceInformation.Attributes.Size = Marshal.SizeOf(deviceInformation.Attributes);
                            var success = Hid.HidD_GetAttributes(deviceInformation.HidHandle, ref deviceInformation.Attributes);

                            if (success)
                            {
                                TmoShare.WriteLog(string.Format("DeviceDiscovery:findTargetDevice() -> 发现设备 VID_{0}, PID_{1} Ver_{2}",
                                                                Convert.ToString(deviceInformation.Attributes.VendorID, 16),
                                                                Convert.ToString(deviceInformation.Attributes.ProductID, 16),
                                                                Convert.ToString(deviceInformation.Attributes.VersionNumber, 16)));

                                //  Do the VID and PID of the device match our target device?
                                if ((deviceInformation.Attributes.VendorID == deviceInformation.TargetVendorId) &&
                                    (deviceInformation.Attributes.ProductID == deviceInformation.TargetProductId))
                                {
                                    // Matching device found
                                    if (string.IsNullOrWhiteSpace(deviceInformation.DevicePathName))
                                    {
                                        deviceInformation.DevicePathName = listOfDevicePathNames[listIndex];
                                        isDeviceDetected = true;
                                        TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 找到目标设备!");
                                    }
                                    else if (string.Compare(deviceInformation.DevicePathName, listOfDevicePathNames[listIndex], true) == 0)
                                    {
                                        isDeviceDetected = true;
                                        TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 找到目标设备!");
                                    }
                                    else
                                    {
                                        TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 不是目标设备... 继续寻找...");
                                        deviceInformation.HidHandle.Close();
                                    }
                                    // Store the device's pathname in the device information
                                }
                                else
                                {
                                    // Wrong device, close the handle
                                    TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 不是目标设备... 继续寻找...");
                                    deviceInformation.HidHandle.Close();
                                }
                            }
                            else
                            {
                                //  Something went rapidly south...  give up!
                                TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 识别设备失败, 继续下一个!");
                                deviceInformation.HidHandle.Close();
                            }
                        }
                        else
                        {
                            TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 句柄创建失败");
                        }

                        //  Move to the next device, or quit if there are no more devices to examine
                        listIndex++;
                    }while (!((isDeviceDetected || (listIndex == numberOfDevicesFound))));
                }

                // If we found a matching device then we need discover more details about the attached device
                // and then open read and write handles to the device to allow communication
                if (isDeviceDetected)
                {
                    // Query the HID device's capabilities (primarily we are only really interested in the
                    // input and output report byte lengths as this allows us to validate information sent
                    // to and from the device does not exceed the devices capabilities.
                    //
                    // We could determine the 'type' of HID device here too, but since this class is only
                    // for generic HID communication we don't care...

                    if (!callOther)
                    {
                        // Open the readHandle to the device
                        TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 开始创建读文件句柄");
                        deviceInformation.ReadHandle = Kernel32.CreateFile(
                            deviceInformation.DevicePathName,
                            Constants.GenericRead,
                            Constants.FileShareRead | Constants.FileShareWrite,
                            IntPtr.Zero,
                            Constants.OpenExisting,
                            Constants.FileFlagOverlapped,
                            0);

                        // Did we open the readHandle successfully?
                        if (deviceInformation.ReadHandle.IsInvalid())
                        {
                            TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 读文件句柄创建失败" + Marshal.GetLastWin32Error());
                            return(false);
                        }

                        //Open the writeHandel to the device
                        TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 开始创建写文件句柄");
                        deviceInformation.WriteHandle = Kernel32.CreateFile(
                            deviceInformation.DevicePathName,
                            Constants.GenericWrite,
                            Constants.FileShareWrite | Constants.FileShareRead,
                            IntPtr.Zero,
                            Constants.OpenExisting, 0, 0);

                        // Did we open the writeHandle successfully?
                        if (deviceInformation.WriteHandle.IsInvalid())
                        {
                            TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 写文件句柄创建失败" + Marshal.GetLastWin32Error());
                            return(false);
                        }
                    }

                    QueryDeviceCapabilities(ref deviceInformation);
                    // Device is now discovered and ready for use, update the status
                    deviceInformation.IsDeviceAttached = true;
                    return(true);
                }

                //  The device wasn't detected.
                TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 未找到目标设备!");
                return(false);
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("DeviceDiscovery:findTargetDevice() -> 发生异常:" + ex.Message);
                return(false);
            }
        }
示例#11
0
        public static bool FindHidDevices(ref string[] listOfDevicePathNames, ref int numberOfDevicesFound)
        {
            TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 开始查找所有HID设备");

            // Initialise the internal variables required for performing the search
            var  bufferSize       = 0;
            var  detailDataBuffer = IntPtr.Zero;
            bool deviceFound;
            var  deviceInfoSet = new IntPtr();
            var  lastDevice    = false;
            int  listIndex;
            var  deviceInterfaceData = new SpDeviceInterfaceData();

            // Get the required GUID
            var systemHidGuid = new Guid();

            Hid.HidD_GetHidGuid(ref systemHidGuid);
            TmoShare.WriteLog(string.Format("DeviceDiscovery:findHidDevices() -> 找到HID设备全局 GUID {0}", systemHidGuid));

            try
            {
                // Here we populate a list of plugged-in devices matching our class GUID (DIGCF_PRESENT specifies that the list
                // should only contain devices which are plugged in)
                TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取所有HID设备句柄");
                deviceInfoSet = SetupApi.SetupDiGetClassDevs(ref systemHidGuid, IntPtr.Zero, IntPtr.Zero, Constants.DigcfPresent | Constants.DigcfDeviceinterface);

                // Reset the deviceFound flag and the memberIndex counter
                deviceFound = false;
                listIndex   = 0;

                deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);

                // Look through the retrieved list of class GUIDs looking for a match on our interface GUID
                do
                {
                    TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取设备信息");
                    var success = SetupApi.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref systemHidGuid, listIndex, ref deviceInterfaceData);

                    if (!success)
                    {
                        TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 已经找到最后一个-停止");
                        lastDevice = true;
                    }
                    else
                    {
                        // The target device has been found, now we need to retrieve the device path so we can open
                        // the read and write handles required for USB communication

                        // First call is just to get the required buffer size for the real request
                        SetupApi.SetupDiGetDeviceInterfaceDetail
                            (deviceInfoSet,
                            ref deviceInterfaceData,
                            IntPtr.Zero,
                            0,
                            ref bufferSize,
                            IntPtr.Zero);

                        // Allocate some memory for the buffer
                        detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
                        Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);

                        // Second call gets the detailed data buffer
                        TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取设备详细信息");
                        SetupApi.SetupDiGetDeviceInterfaceDetail
                            (deviceInfoSet,
                            ref deviceInterfaceData,
                            detailDataBuffer,
                            bufferSize,
                            ref bufferSize,
                            IntPtr.Zero);

                        // Skip over cbsize (4 bytes) to get the address of the devicePathName.
                        var pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4);

                        // Get the String containing the devicePathName.
                        listOfDevicePathNames[listIndex] = Marshal.PtrToStringAuto(pDevicePathName).ToUpper();

                        TmoShare.WriteLog(string.Format("DeviceDiscovery:findHidDevices() -> 将找到的设备添加进列表 (索引 {0})", listIndex));
                        deviceFound = true;
                        listIndex++;
                    }
                }while (lastDevice != true);
            }
            catch (Exception ex)
            {
                // Something went badly wrong... output some debug and return false to indicated device discovery failure
                TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 发生异常: " + ex.Message);
                return(false);
            }
            finally
            {
                // Clean up the unmanaged memory allocations
                if (detailDataBuffer != IntPtr.Zero)
                {
                    // Free the memory allocated previously by AllocHGlobal.
                    Marshal.FreeHGlobal(detailDataBuffer);
                }

                if (deviceInfoSet != IntPtr.Zero)
                {
                    SetupApi.SetupDiDestroyDeviceInfoList(deviceInfoSet);
                }
            }

            if (deviceFound)
            {
                TmoShare.WriteLog(String.Format("DeviceDiscovery:findHidDevices() -> 一共找到{0}个HID设备", listIndex));
                numberOfDevicesFound = listIndex;
            }
            else
            {
                TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 没有找到HID设备");
            }

            return(deviceFound);
        }
示例#12
0
        void btnLogin_Click(object sender, EventArgs e)
        {
            if (!dxvalidation.Validate() || string.IsNullOrWhiteSpace(txtUid.Text))
            {
                DXMessageBox.Show("用户名和密码不能为空!", MessageIcon.Info, MessageButton.OK);
            }
            else
            {
                string uidmd5 = DESEncrypt.Encrypt(txtUid.Text);
                string pwdmd5 = DESEncrypt.Encrypt(txtPwd.Text);
                uidmd5 = StringPlus.CompressString(uidmd5);
                pwdmd5 = StringPlus.CompressString(pwdmd5);
                try
                {
                    this.loginPress.Show();
                    btnLogin.Enabled = btnCancel.Enabled = chkAutoLogin.Enabled = false;
                    this.CrossThreadCallsSync(x =>
                    {
                        this.loginPress.Hide();
                        btnLogin.Enabled = btnCancel.Enabled = chkAutoLogin.Enabled = true;
                        string rtCode    = x as string;
                        switch (rtCode)
                        {
                        case "err_uid":
                            DXMessageBox.ShowWarning("用户名不存在!");
                            txtUid.Focus();
                            break;

                        case "err_pwd":
                            DXMessageBox.ShowWarning("密码错误!");
                            txtPwd.Focus();
                            break;

                        default:
                            if (!string.IsNullOrWhiteSpace(rtCode) && rtCode.Length > 1)
                            {
                                #region 错误信息处理
                                if (rtCode.StartsWith("err_"))
                                {
                                    DXMessageBox.ShowError(rtCode.Substring(4));
                                    return;
                                }
                                #endregion

                                #region 本地记住用户名和密码
                                if (chkAutoLogin.Checked)
                                {
                                    ConfigHelper.UpdateConfig("u", uidmd5, true);
                                    ConfigHelper.UpdateConfig("p", pwdmd5, true);
                                }
                                #endregion

                                DataTable dt = TmoShare.getDataTableFromXML(StringPlus.DecompressString(rtCode));
                                DataRow dr   = dt.Rows[0];
                                //用户编号 用户姓名
                                Userinfo user = new Userinfo()
                                {
                                    user_id = dr.GetDataRowStringValue("user_id"), name = dr.GetDataRowStringValue("name")
                                };
                                TmoComm.login_userInfo = user;

                                DXMessageBox.Show(string.Format("用户【{0}】登录成功!", TmoComm.login_userInfo.name), true);

                                if (this.ParentForm != null)
                                {
                                    this.ParentForm.DialogResult = DialogResult.OK;
                                    this.ParentForm.Close();
                                }
                            }
                            else
                            {
                                TmoShare.WriteLog("登录失败", "未知错误:返回值->" + rtCode);
                                DXMessageBox.ShowError("未知错误!");
                            }
                            break;
                        }
                    }, () =>
                    {
                        try
                        {
                            WebServiceDLL.MonitorService service = new WebServiceDLL.MonitorService();
                            return(service.UserLogin(uidmd5, pwdmd5));
                        }
                        catch
                        { return("err_与服务器通信失败!请检查网络连接"); }
                    });
                }
                catch (Exception ex)
                {
                    TmoShare.WriteLog("登录失败", ex);
                    DXMessageBox.ShowError("与服务器通信失败!请检查网络连接");
                }
            }
        }
示例#13
0
        /// <summary>
        /// registerForDeviceNotification - registers the window (identified by the windowHandle) for
        /// device notification messages from Windows
        /// </summary>
        public bool RegisterForDeviceNotifications(IntPtr windowHandle1)
        {
            TmoShare.WriteLog("usbGenericHidCommunication:registerForDeviceNotifications() -> Method called");

            // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request.
            var devBroadcastDeviceInterface       = new DevBroadcastDeviceinterface();
            var devBroadcastDeviceInterfaceBuffer = IntPtr.Zero;

            // Get the required GUID
            var systemHidGuid = new Guid();

            Hid.HidD_GetHidGuid(ref systemHidGuid);

            try
            {
                // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure.
                var size = Marshal.SizeOf(devBroadcastDeviceInterface);
                devBroadcastDeviceInterface.dbcc_size       = size;
                devBroadcastDeviceInterface.dbcc_devicetype = Constants.DbtDevtypDeviceinterface;
                devBroadcastDeviceInterface.dbcc_reserved   = 0;
                devBroadcastDeviceInterface.dbcc_classguid  = systemHidGuid;

                devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
                // Register for notifications and store the returned handle
                DeviceNotificationHandle = User32.RegisterDeviceNotification(Handle, devBroadcastDeviceInterfaceBuffer, Constants.DeviceNotifyWindowHandle);

                Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface);

                if ((DeviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32()))
                {
                    TmoShare.WriteLog(
                        "usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration failed");
                    return(false);
                }
                else
                {
                    TmoShare.WriteLog(
                        "usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration succeded");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog(
                    "usbGenericHidCommunication:registerForDeviceNotifications() -> EXCEPTION: An unknown exception has occured!");
                TmoShare.WriteLog(ex.Message);
            }
            finally
            {
                // Free the memory allocated previously by AllocHGlobal.
                if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero)
                {
                    try
                    {
                        Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer);
                    }
                    catch (Exception ex)
                    {
                        TmoShare.WriteLog(ex.Message);
                    }
                }
            }

            return(false);
        }
示例#14
0
        /// <summary>
        /// 加载数据
        /// </summary>
        public void GetData()
        {
            this.ShowWaitingPanel(() =>
            {
                try
                {
                    _dsQueryXml = TmoShare.getDataSetFromXML(SubmitXml, true);

                    if (_dsQueryXml.Tables[0].Rows.Count == 0)
                    {
                        _dsQueryXml.Tables[0].Rows.Add(_dsQueryXml.Tables[0].NewRow());
                    }
                    _dsQueryXml.Tables[0].Rows[0]["doc_code"]  = TmoComm.login_docInfo.children_docid;
                    _dsQueryXml.Tables[0].Rows[0]["page_size"] = _pageSize.ToString();
                    _dsQueryXml.Tables[0].Rows[0]["now_page"]  = _currentPage.ToString();
                    if (!string.IsNullOrEmpty(this.user_codetxt.Text))
                    {
                        _dsQueryXml.Tables[0].Rows[0]["user_id"] = this.user_codetxt.Text;
                    }

                    if (!string.IsNullOrEmpty(this.user_timestxt.Text))
                    {
                        _dsQueryXml.Tables[0].Rows[0]["user_times"] = this.user_timestxt.Text;
                    }
                    if (!string.IsNullOrEmpty(this.user_nametxt.Text))
                    {
                        _dsQueryXml.Tables[0].Rows[0]["name"] = this.user_nametxt.Text;
                    }
                    string gender = cmgender.EditValue.ToString();
                    if (gender == "男")
                    {
                        _dsQueryXml.Tables[0].Rows[0]["gender"] = "1";
                    }
                    if (gender == "女")
                    {
                        _dsQueryXml.Tables[0].Rows[0]["gender"] = "2";
                    }

                    if (birchb.Checked)
                    {
                        _dsQueryXml.Tables[0].Rows[0]["birth_date_begin"] = birth_datestart.EditValue.ToString();
                        _dsQueryXml.Tables[0].Rows[0]["birth_date_end"]   = birth_dateend.EditValue.ToString();
                    }
                    if (checkEdit2.Checked)
                    {
                        _dsQueryXml.Tables[0].Rows[0]["reg_time_begin"] = exam_timestart.EditValue.ToString();
                        _dsQueryXml.Tables[0].Rows[0]["reg_time_end"]   = exam_timeend.EditValue.ToString();
                    }
                    string selexml = TmoShare.getXMLFromDataSet(_dsQueryXml);

                    string strmlx    = TmoReomotingClient.InvokeServerMethod(funCode.GetNewServiceData, new object[] { selexml }).ToString();
                    _dsGetDataResult = TmoShare.getDataSetFromXML(strmlx);
                    if (TmoShare.DataSetIsNotEmpty(_dsGetDataResult))
                    {
                        DataTable dtCount = _dsGetDataResult.Tables["Count"];
                        count             = dtCount.Rows[0]["totalRowCount"].ToString();
                        double countnum   = double.Parse(count) / _pageSize;
                        pageCount         = Math.Ceiling(countnum).ToString();
                        return(_dsGetDataResult.Tables[1]);
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch
                { }
                return(null);
            }, x =>
            {
                try
                {
                    DataTable dt = x as DataTable;
                    if (dt != null)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            row["buy_service"] = "延伸服务";
                        }
                    }
                    dgcTree.DataSource = dt;
                    if (gridView1.GroupCount > 0)
                    {
                        gridView1.ExpandAllGroups();
                    }
                    gridView1.MoveFirst();
                    if (dt == null)
                    {
                        return;
                    }

                    lblCount.Text     = string.Format("共[{0}]条", count);
                    lblPageIndex.Text = string.Format("第[{0}]页,共[{1}]页", _currentPage.ToString(), _pageSize.ToString());
                    txtPageIndex.Text = _currentPage.ToString();
                    txtPageSize.Text  = _pageSize.ToString();

                    llblUp.Enabled   = _currentPage > 1;
                    llblDown.Enabled = _currentPage < int.Parse(pageCount);
                }
                catch (Exception ex)
                {
                    TmoShare.WriteLog("实体加载数据出错", ex);
                    DXMessageBox.ShowWarning2("数据加载失败!请重试!");
                }
            });
        }