Example #1
0
        private void workerDoWork(object sender, DoWorkEventArgs e)
        {
            do
            {
                //Console.WriteLine(BTDevice.Connected);
                // If Scanner is connected
                BTDevice.Refresh();
                if (BTDevice.Connected)
                {
                    this.DeviceFound = true;
                    //this.OnPropertyChanged("DeviceFound");
                    Console.WriteLine("Device connected");
                    if (!BC.Connected)
                    {
                        this.DeviceConnected = true;
                        Console.WriteLine("BC Connected");
                        if (BluetoothSecurity.PairRequest(BTDevice.DeviceAddress, "1234"))
                        {
                            Console.WriteLine("PairRequest: OK");

                            if (BTDevice.Authenticated)
                            {
                                Console.WriteLine("Authenticated: OK");

                                //BC.SetPin("1234");

                                BC.BeginConnect(BTDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), BTDevice);

                                System.Threading.Thread.Sleep(200);
                                //BC.Close();
                            }
                            else
                            {
                                Console.WriteLine("Authenticated: No");
                            }
                        }
                        else
                        {
                            Console.WriteLine("PairRequest: No");
                        }
                    }
                    this.DeviceConnected = false;
                    System.Threading.Thread.Sleep(5000);
                }
                else
                {
                    this.DeviceFound = false;
                    //this.OnPropertyChanged("DeviceFound");
                    Console.WriteLine("Refresh Device Status");
                    BTDevice.Refresh();
                    System.Threading.Thread.Sleep(5000);
                }
            } while (true);
        }
Example #2
0
        static void Main(string[] args)
        {
            BluetoothClient client = new BluetoothClient();

            BluetoothDeviceInfo device = null;

            foreach (var dev in client.DiscoverDevices())
            {
                if (dev.DeviceName.Contains("PREFIX"))
                {
                    device = dev;
                    break;
                }
            }

            if (!device.Authenticated)
            {
                BluetoothSecurity.PairRequest(device.DeviceAddress, "1234");
            }

            device.Refresh();
            System.Diagnostics.Debug.WriteLine(device.Authenticated);

            client.Connect(device.DeviceAddress, BluetoothService.SerialPort);

            var          stream = client.GetStream();
            StreamWriter sw     = new StreamWriter(stream, System.Text.Encoding.ASCII);

            sw.WriteLine("Hello world!\r\n\r\n");
            sw.Close();

            client.Close();
        }
Example #3
0
        static bool DoPairRequest(BluetoothAddress device, string pin)
        {
            if (pin.Length > BLUETOOTH_PIN_INFO.BTH_MAX_PIN_SIZE)
            {
                throw new ArgumentOutOfRangeException(nameof(pin));
            }

            BLUETOOTH_DEVICE_INFO info = new BLUETOOTH_DEVICE_INFO();

            info.dwSize  = Marshal.SizeOf(info);
            info.Address = device;

            RemoveRedundantAuthHandler(device);

            // Handle response without prompt
            _authenticationHandlers.Add(new Win32BluetoothAuthentication(device, pin));

            bool success = NativeMethods.BluetoothAuthenticateDeviceEx(IntPtr.Zero, IntPtr.Zero, ref info, null, BluetoothAuthenticationRequirements.MITMProtectionNotRequired) == 0;

            BluetoothDeviceInfo deviceInfo = new BluetoothDeviceInfo(info);

            deviceInfo.Refresh();

            // On Windows 7 these services are not automatically activated
            if (deviceInfo.ClassOfDevice.Device == DeviceClass.AudioVideoHeadset || deviceInfo.ClassOfDevice.Device == DeviceClass.AudioVideoHandsFree)
            {
                deviceInfo.SetServiceState(BluetoothService.Headset, true);
                deviceInfo.SetServiceState(BluetoothService.Handsfree, true);
            }

            return(success);
        }
Example #4
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (dataGridView1.Rows.Count == 0)
     {
         MessageBox.Show("Nie skanowano w poszukiwaniu urządzeń!", "BŁĄD!");
         return;
     }
     if (selectedDevice[0] == "<NULL>")
     {
         MessageBox.Show("Brak urzadzeń do sparowania!", "BŁĄD!");
         return;
     }
     if (isPaired)
     {
         BluetoothDeviceInfo[] paired = localClient.DiscoverDevices(255, false, true, false, false);
         if (paired[0].DeviceName == selectedDevice[1])
         {
             return;
         }
         BluetoothSecurity.RemoveDevice(paired[0].DeviceAddress);
     }
     selected.Update();
     selected.Refresh();
     selected.SetServiceState(BluetoothService.ObexObjectPush, true);
     //localClient.Connect(new BluetoothEndPoint(selected.DeviceAddress, BluetoothService.ObexFileTransfer));
     BluetoothSecurity.PairRequest(selected.DeviceAddress, null);
     isPaired = true;
 }
        private void sendFileButton_Click(object sender, EventArgs e)
        {
            if (device == null)
            {
                MessageBox.Show("Nie wybrano urządzenia!!!");
                return;
            }

            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                device.Update();
                device.Refresh();
                device.SetServiceState(BluetoothService.ObexObjectPush, true);

                var file    = ofd.FileName;
                var uri     = new Uri("obex://" + device.DeviceAddress + "/" + file);
                var request = new ObexWebRequest(uri);
                request.ReadFile(file);

                ObexWebResponse response = null;
                try
                {
                    response = (ObexWebResponse)request.GetResponse();
                    MessageBox.Show(response.StatusCode.ToString());
                    response.Close();
                }catch (Exception)
                {
                    // check response.StatusCode
                    MessageBox.Show("Urządzenie nie odpowiedziło");
                }
            }
        }
Example #6
0
        private void buttonPair_Click(object sender, EventArgs e)
        {
            //wybieramy urządzenie z listy
            foreach (BluetoothDeviceInfo device in devices)
            {
                if (device.DeviceName.Equals(listBoxDevices.SelectedItem))
                {
                    deviceToPair = device;
                }
            }

            //nawiżaywanie połączneia z wybranym urządzeniem
            deviceToPair.Update();
            deviceToPair.Refresh();
            deviceToPair.SetServiceState(BluetoothService.ObexObjectPush, true);

            //wysłanie podłączenia
            string pin = "1234";

            isPaired = BluetoothSecurity.PairRequest(deviceToPair.DeviceAddress, pin);

            //wypisanie wszystkich sparowanych urządzeń
            if (isPaired)
            {
                connected.Add(deviceToPair);
                listBoxConnected.Items.Clear();
                foreach (var device in connected)
                {
                    listBoxConnected.Items.Add(device.DeviceName);
                }
            }
        }
 /// <summary>
 /// if the name didn't come in yet we get an address
 /// formatted like "F4:FC:32:1B:1F:16".  if the given
 /// device has a name of that format, ask for it again
 /// </summary>
 /// <param name="device"></param>
 /// <returns></returns>
 public string GetDeviceName(BluetoothDeviceInfo device)
 {
     if (device.DeviceName.IsBluetoothAddress())
     {
         System.Threading.Thread.Sleep(1000);
         device.Refresh();
     }
     return(device.DeviceName);
 }
Example #8
0
        private void WiiConnectStart()
        {
            BluetoothSecurity.RemoveDevice(wiidevice.DeviceAddress);

            wiidevice.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
            wiidevice.Refresh();
            System.Threading.Thread.Sleep(500);
            localClient.BeginConnect(wiidevice.DeviceAddress, BluetoothService.HumanInterfaceDevice, new AsyncCallback(Connect), wiidevice);
        }
Example #9
0
 private void button_Click(object sender, EventArgs e)
 {
     if (selectedDevice != null)
     {
         selectedDevice.Update();
         selectedDevice.Refresh();
         if (BluetoothSecurity.PairRequest(selectedDevice.DeviceAddress, "0000"))
         {
             bluetoothClient.BeginConnect(selectedDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), selectedDevice);
         }
     }
 }
Example #10
0
        private void PairWithClient()
        {
            //sprawdzamy ktory wybrany z list boxa
            foreach (var client in clients)
            {
                if (client.DeviceName == (string)listBox1.SelectedItem)
                {
                    deviceToPair = client;
                }
            }

            if (deviceToPair != null)
            {
                textBox1.Text += ("Urzadzenie, z ktorym sie parujemy:") + Environment.NewLine;
                var blueToothInfo =
                    string.Format(
                        "- DeviceName: {0}{1}  Connected: {2}{1}  Address: {3}{1}  Last seen: {4}{1}  Last used: {5}{1}",
                        deviceToPair.DeviceName, Environment.NewLine, deviceToPair.Connected, deviceToPair.DeviceAddress, deviceToPair.LastSeen,
                        deviceToPair.LastUsed);
                blueToothInfo += string.Format("  Class of device{0}   Device: {1}{0}   Major Device: {2}{0}   Service: {3}",
                                               Environment.NewLine, deviceToPair.ClassOfDevice.Device, deviceToPair.ClassOfDevice.MajorDevice, deviceToPair.ClassOfDevice.Service);
                textBox1.Text += (blueToothInfo) + Environment.NewLine;

                deviceToPair.Update();
                deviceToPair.Refresh();
                deviceToPair.SetServiceState(BluetoothService.ObexObjectPush, true);
                bool isPaired = BluetoothSecurity.PairRequest(deviceToPair.DeviceAddress, DEVICE_PIN);
                if (isPaired)
                {
                    textBox1.Text += ("Urzadzenie sparowane!") + Environment.NewLine;
                    listBox2.Items.Add(deviceToPair.DeviceName);

                    czySparowano = true;

                    // jezeli sparowano to aktywujemy tryb nasluchu plikow

                    Thread thread = new Thread(ReceiveFile);
                    thread.Priority     = ThreadPriority.Normal;
                    thread.IsBackground = true;
                    thread.Start();
                }
                else
                {
                    textBox1.Text += ("Urzadzenie niesparowane!") + Environment.NewLine;
                }
            }
            else
            {
                MessageBox.Show("Nie wybrano urzadzenia do sparowania!");
            }
            button2.Enabled = true;
        }
Example #11
0
        //--------------Blue Tooth Connection Section-------------------
        private void SearchWiimote()
        {
            if (m_Connected)
            {
                finelizeWiiMoteConnection();
            }
            else
            {
                BluetoothClient       btClient        = new BluetoothClient();
                BluetoothDeviceInfo[] devices         = btClient.DiscoverDevicesInRange();
                BluetoothDeviceInfo   DeviceToConnect = getWiiMoteBTDevice(devices);
                if (DeviceToConnect == null)
                {
                    devices         = btClient.DiscoverDevicesInRange();
                    DeviceToConnect = getWiiMoteBTDevice(devices);
                    if (DeviceToConnect == null)
                    {
                        fireConnectionStateChangeEvent(eWiiConnectivityState.Not_Found);
                    }
                }
                else if (checkWiiMoteConnectionAbility(DeviceToConnect))
                {
                    fireConnectionStateChangeEvent(eWiiConnectivityState.Connecting);
                    if (DeviceToConnect.InstalledServices.Length != 0)
                    {
                        BluetoothSecurity.RemoveDevice(DeviceToConnect.DeviceAddress);
                    }

                    if (!DeviceToConnect.Remembered)
                    {
                        DeviceToConnect.Refresh();
                        btClient.BeginConnect(DeviceToConnect.DeviceAddress, r_UUID, connectionCallbackFunction, btClient);
                        DeviceToConnect.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
                    }

                    try
                    {
                        finelizeWiiMoteConnection();
                    }
                    catch (Exception)
                    {
                        fireConnectionStateChangeEvent(eWiiConnectivityState.Failed_To_Connect);
                    }
                }
                else
                {
                    fireConnectionStateChangeEvent(eWiiConnectivityState.Failed_To_Connect);
                }
            }
        }
        public void FromAddress()
        {
            BluetoothDeviceInfo bdi = Create1_FromAddress();

            Assert.IsFalse(bdi.Connected, "Connected");
            Assert.IsFalse(bdi.Remembered, "Remembered");
            Assert.IsFalse(bdi.Authenticated, "Authenticated");
            Assert.AreEqual(DateTime.MinValue, bdi.LastSeen, "LastSeen");
            Assert.AreEqual(DateTime.MinValue, bdi.LastUsed, "LastUsed");
            Assert.AreEqual(0, bdi.ClassOfDevice.ValueAsInt32, "ClassOfDevice");
            Assert.AreEqual(Addr1, bdi.DeviceAddress, "DeviceAddress");
            Assert.AreEqual(Addr1.ToString("C"), bdi.DeviceName, "DeviceName");
            //
            //
            bdi.Refresh(); // Refresh has no effect on Widcomm (yet).
            Assert.AreEqual(Addr1.ToString("C"), bdi.DeviceName, "DeviceName after Refresh");
            //
            bdi.DeviceName = "foobar";
            Assert.AreEqual("foobar", bdi.DeviceName, "DeviceName after set");
            //
            bdi.Refresh(); // Refresh has no effect on Widcomm (yet).
            Assert.AreEqual("foobar", bdi.DeviceName, "DeviceName after set&Refresh");
        }
        public void FromInquiry_NotConnected()
        {
            BluetoothDeviceInfo bdi = Create2_FromInquiry_NotConnected();

            Assert.IsFalse(bdi.Connected, "Connected");
            Assert.IsFalse(bdi.Remembered, "Remembered");
            Assert.IsFalse(bdi.Authenticated, "Authenticated");
            Assert.AreEqual(DateTime.MinValue, bdi.LastSeen, "LastSeen");
            Assert.AreEqual(DateTime.MinValue, bdi.LastUsed, "LastUsed");
            Assert.AreEqual(devClass2, bdi.ClassOfDevice.ValueAsInt32, "ClassOfDevice");
            Assert.AreEqual(Addr2, bdi.DeviceAddress, "DeviceAddress");
            Assert.AreEqual(name2, bdi.DeviceName, "DeviceName");
            //
            //
            bdi.Refresh(); // Refresh has no effect on Widcomm (yet).
            Assert.AreEqual(name2, bdi.DeviceName, "DeviceName after set&Refresh");
        }
Example #14
0
        /// <summary>
        /// refresh device information or find the device requred
        /// </summary>
        ///
        /// <param name="myDevInfo">
        /// initial device information to be used
        /// </param>
        ///
        /// <returns>
        /// updated device information
        /// </returns>
        private BluetoothDeviceInfo RefreshDeviceInfo(
            BluetoothDeviceInfo myDevInfo)
        {
            /* devices discovered by single scan */
            BluetoothDeviceInfo[] infos;

            /* if the device info is already set, just refresh it */
            if (myDevInfo != null)
            {
                myDevInfo.Refresh();
                return(myDevInfo);
            }

            infos = m_btClient.DiscoverDevices();
            return(infos.FirstOrDefault(inf =>
                                        inf.DeviceAddress.Equals(m_deviceAddress)));
        }
Example #15
0
        // Funkcja która łączy adapter z urządzeniem bluetooth
        public void Connect(ListBox devices)
        {
            // Pobranie informacji o wybranym urządzeniu
            BluetoothDeviceInfo device = info[devices.SelectedIndex];

            // Aktualizacja nazwy urządzenia
            device.Update();
            // Odświeżenie informacji o urządzeniu
            device.Refresh();
            // Przygotowanie urządzenia do wysyłania danych binarnych z wykorzystaniem protokołu OBEX
            device.SetServiceState(BluetoothService.ObexObjectPush, true);

            EventHandler <BluetoothWin32AuthenticationEventArgs> handler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(HandleRequests);
            BluetoothWin32Authentication auth = new BluetoothWin32Authentication(handler);

            // Jeżeli urządzenie nie jest sparowane zostaje wysłana prośba o sparowanie, musi zostać ona potwierdzona podaniem pinu - 123456
            if (!device.Authenticated)
            {
                BluetoothSecurity.PairRequest(device.DeviceAddress, "123456");
            }
        }
Example #16
0
        private void PairWithDevice()
        {
            foreach (var device in devices)
            {
                if (device.DeviceName == (string)listBoxDevices.SelectedItem)
                {
                    deviceToPair = device;
                }
            }

            if (deviceToPair == null)
            {
                textBoxConsole.Text += "Nie wybrano urządzenia do sparowania!\r\n";
            }
            else
            {
                textBoxConsole.Text += "Parowanie z urządzeniem " + (string)deviceToPair.DeviceName + "...\r\n";
                deviceToPair.Update();
                deviceToPair.Refresh();
                deviceToPair.SetServiceState(BluetoothService.ObexObjectPush, true);
                isPaired = BluetoothSecurity.PairRequest(deviceToPair.DeviceAddress, DEVICE_PIN);
                if (isPaired)
                {
                    textBoxConsole.Text += "Urządzenie sparowane pomyślnie.\r\n";
                    listBoxConnected.Items.Add(deviceToPair.DeviceName);
                    buttonPairWithDevice.Enabled = false;
                    buttonUnpair.Enabled         = true;

                    Thread receiveFiles = new Thread(ReceiveFiles);
                    receiveFiles.Priority     = ThreadPriority.Highest;
                    receiveFiles.IsBackground = true;
                    receiveFiles.Start();
                }
                else
                {
                    textBoxConsole.Text += "Nie udało się sparować urządzenia.\r\n";
                }
            }
        }
Example #17
0
        /// <summary>
        /// test if the device specified by "deviceAddress" is connected
        /// </summary>
        ///
        /// <param name="info">
        /// device being monitored
        /// </param>
        ///
        /// <returns>
        /// true if the device is connected */
        /// </returns>
        private bool IsInRange(BluetoothDeviceInfo info)
        {
            /* ensure that the settings are updated */
            m_settings.Reload();

            /* no device -> no connection */
            if (info == null)
            {
                return(false);
            }

            info.Refresh();

            /* if this device is already connected -> we are good */
            if (info.Connected)
            {
                return(true);
            }

            for (var retries = 0; ; retries++)
            {
                try
                {
                    info.GetServiceRecords(BluetoothService.Headset);
                    break;
                }
                catch (SocketException)
                {
                    if (retries >= m_settings.ConnectionRetries)
                    {
                        return(false);
                    }
                    retries++;
                    continue;
                }
            }

            return(true);
        }
Example #18
0
        // Funkcja ta wysyła plik do urządzenia bluetooth
        public void SendFile(ListBox devices)
        {
            // Pobranie informacji o wybranym urządzeniu
            BluetoothDeviceInfo device = info[devices.SelectedIndex];

            // Aktualizacja nazwy urządzenia
            device.Update();
            // Odświeżenie informacji o urządzeniu
            device.Refresh();
            // Przygotowanie urządzenia do wysyłania danych binarnych z wykorzystaniem protokołu OBEX
            device.SetServiceState(BluetoothService.ObexObjectPush, true);

            OpenFileDialog window = new OpenFileDialog();

            window.ShowDialog(); //wyświetlenie okienka do wyboru pliku
            var file = window.FileName;
            // Ustalenie ścieżki pliku
            var uri = new Uri("obex://" + device.DeviceAddress + "/" + file);
            // Stworzenie zapytania ze ścieżką pliku
            var request = new ObexWebRequest(uri);

            // Przeczytanie zawartości pliku
            request.ReadFile(file);
            // Wysłanie zapytania oraz pobranie odpowiedzi
            var response = request.GetResponse() as ObexWebResponse;

            // Wyświetlenie komunikatu czy przesyłanie pliku przebiegło pomyślnie
            if (response.StatusCode.ToString() == "OK, Final")
            {
                MessageBox.Show("Plik przesłany pomyślnie");
            }
            else
            {
                MessageBox.Show("Błąd przesyłania pliku");
            }
            // Zakończenie wymiany informacji z urządzeniem
            response.Close();
        }
Example #19
0
        private static bool BluetoothIdleLoop(CancellationToken token)
        {
            var wiimoteList = ConnectedWiimotes;

            if (wiimoteList.Length == 0)
            {
                return(false);
            }

            foreach (Wiimote wiimote in wiimoteList)
            {
                if (token.IsCancellationRequested)
                {
                    return(false);
                }
                //FIXME: Quick fix to support both DolphinBar and Bluetooth connections.
                if (!wiimote.Device.IsBluetooth)
                {
                    continue;
                }
                BluetoothDeviceInfo device = wiimote.Device.Bluetooth;
                Stopwatch           watch2 = Stopwatch.StartNew();
                device.Refresh();
                Debug.WriteLine($"Took {watch2.ElapsedMilliseconds}ms refresh {device}");
                if (!device.Connected)
                {
                    lock (wiimotes) {
                        wiimote.Dispose();
                        wiimotes.Remove(wiimote);
                        RaiseDisconnected(wiimote, DisconnectReason.ConnectionLost);
                    }
                }
                token.Sleep(100);
            }
            token.Sleep(1500);
            return(true);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.Text.Equals("Thay đổi Câu hỏi Bí mật"))
            {
                using (Form3 frm3 = new Form3())
                {
                    frm3.ShowDialog();
                }
                Close();
                return;
            }

            if (this.Text.Equals("Thay đổi thiết bị"))
            {
                InTheHand.Windows.Forms.SelectBluetoothDeviceDialog dialog = new InTheHand.Windows.Forms.SelectBluetoothDeviceDialog();
                DialogResult result = dialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    BluetoothDeviceInfo selected = dialog.SelectedDevice;
                    BluetoothClient     bc       = new BluetoothClient();
                    if (selected.Authenticated == false)
                    {
                        bool paired = BluetoothSecurity.PairRequest(selected.DeviceAddress, null);
                        if (!paired)
                        {
                            //Không thể repair
                            MessageBox.Show("Không thể Pair thiết bị", "Pair không thành công", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    if (bc.Connected == false)
                    {
                        try
                        {
                            bc.Connect(new BluetoothEndPoint(selected.DeviceAddress, InTheHand.Net.Bluetooth.BluetoothService.Handsfree)); //.BluetoothService.SerialPort
                            selected.SetServiceState(InTheHand.Net.Bluetooth.BluetoothService.Handsfree, true);                            //.BluetoothService.SerialPort
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Thiết bị Bluetooth không hỗ trợ dịch vụ Hands-Free", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.Close();
                            return;
                        }
                    }
                    selected.Refresh();
                    if (selected.Connected)
                    {
                        try
                        {
                            connectDatabase();
                            string       stm1 = "UPDATE `folderlock`.`device` SET `MacAddress`='" + selected.DeviceAddress.ToString() + "' WHERE `id`='1'";
                            MySqlCommand cmd1 = new MySqlCommand(stm1, conn);
                            cmd1.ExecuteNonQuery();

                            AnswerSuccess = true;
                            Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Không thể thay đổi thiết bị trong cơ sở dữ liệu", "Không thể thay đổi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        //Không thể connect
                        MessageBox.Show("Không thể kết nối với thiết bị", "Không thành công", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
                return;
            }

            if (textBox2.Text.Trim().Equals(""))
            {
                MessageBox.Show("Bạn vui lòng chọn câu hỏi", "Chọn câu hỏi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (textBox1.Text.Trim().Equals(""))
            {
                MessageBox.Show("Bạn vui lòng nhập vào câu trả lời", "Trả lời câu hỏi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            connectDatabase();
            string          stm = "SELECT answer FROM folderlock.recovery where question like '" + textBox2.Text + "'";
            MySqlCommand    cmd = new MySqlCommand(stm, conn);
            MySqlDataReader rdr = null;

            rdr = cmd.ExecuteReader();
            if (rdr.Read())
            {
                if (rdr.GetString(0).Equals(textBox1.Text))
                {
                    //trả lời đúng
                    DialogResult mess = MessageBox.Show("Đã trả lời đúng câu hỏi. Bạn có muốn chọn thiết bị điện thoại khác để đăng nhập?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (mess == DialogResult.Yes)
                    {
                        InTheHand.Windows.Forms.SelectBluetoothDeviceDialog dialog = new InTheHand.Windows.Forms.SelectBluetoothDeviceDialog();
                        DialogResult result = dialog.ShowDialog();

                        if (result == DialogResult.OK)
                        {
                            BluetoothDeviceInfo selected = dialog.SelectedDevice;
                            //BluetoothDeviceInfo bd;
                            BluetoothClient bc = new BluetoothClient();
                            if (selected.Authenticated == false)
                            {
                                bool paired = BluetoothSecurity.PairRequest(selected.DeviceAddress, null);
                                if (!paired)
                                {
                                    //Không thể repair
                                    MessageBox.Show("Không thể Pair thiết bị", "Pair không thành công", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }
                            if (bc.Connected == false)
                            {
                                try
                                {
                                    bc.Connect(new BluetoothEndPoint(selected.DeviceAddress, InTheHand.Net.Bluetooth.BluetoothService.Handsfree)); //.BluetoothService.SerialPort
                                    selected.SetServiceState(InTheHand.Net.Bluetooth.BluetoothService.Handsfree, true);                            //.BluetoothService.SerialPort
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Thiết bị Bluetooth không hỗ trợ dịch vụ Hands-Free", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    this.Close();
                                    return;
                                }
                            }
                            selected.Refresh();
                            if (selected.Connected)
                            {
                                try
                                {
                                    connectDatabase();
                                    string       stm1 = "UPDATE `folderlock`.`device` SET `MacAddress`='" + selected.DeviceAddress.ToString() + "' WHERE `id`='1'";
                                    MySqlCommand cmd1 = new MySqlCommand(stm1, conn);
                                    cmd1.ExecuteNonQuery();
                                    MessageBox.Show("Đã thay đổi thành công thiết bị đăng truy cập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    AnswerSuccess = false;
                                    getMacEvent();
                                    Close();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Không thể thay đổi thiết bị trong cơ sở dữ liệu", "Không thể thay đổi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            else
                            {
                                //Không thể connect
                                MessageBox.Show("Không thể kết nối với thiết bị", "Không thành công", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            return;
                        }
                        return;
                    }
                    else
                    {
                        if (ChangeSizeMainFormEvent != null)
                        {
                            ChangeSizeMainFormEvent(463, 383);
                        }
                        AnswerSuccess = true;
                        this.Close();
                        return;
                    }
                    //Close();
                }
                else
                {
                    //trả lời sai
                    DialogResult mess1 = MessageBox.Show("Bạn đã trả lời sai câu hỏi. Bạn có muốn trả lời lại câu hỏi không?", "Trả lời sai câu hỏi", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                    if (mess1 == DialogResult.No)
                    {
                        this.Close();
                    }
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy câu hỏi trong Cơ Sở Dữ Liệu", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
        }
Example #21
0
 /// <summary>
 /// Forces the system to refresh the device information.
 /// </summary>
 public void Refresh()
 {
     _deviceInfo?.Refresh();
 }
Example #22
0
 public void Refresh()
 {
     _btDeviceInfo.Refresh();
 }