Hiển thị các bài đăng có nhãn DOWNLOAD. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn DOWNLOAD. Hiển thị tất cả bài đăng

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn cách tìm kiếm Tiếng Việt không dấu highlight có dấu trên Devexpress Winform C#.

[DEVEXPRESS] Tìm kiếm không dấu tô màu highlight có dấu trên C# Winform


Hình ảnh tìm kiếm không dấu có thể highlight có dấu Tiếng Việt:

Ở hình ảnh trên, các bạn thấy mình gõ vào từ khóa: cam thuy quang
=> kết quả nó tự hiểu và tìm kiếm Cam Thủy, Quảng Bình...

Video demo ứng dụng:


FULL SOURCE CODE CSHARP:

using DevExpress.XtraEditors.Controls;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Globalization;
using DevExpress.Utils.Paint;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils.Html.Internal;
using DevExpress.XtraPrinting.Native;
using DevExpress.XtraPrinting;
using DevExpress.XtraEditors;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace SearchHighLightNoneVietnamese
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        private List<DVHC> listDVHC = new List<DVHC>();
        public Color foreColorHighLight = Color.White;
        public Color backgroundColorHighLight = Color.YellowGreen;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            colorBackground.Color = backgroundColorHighLight;
            colorForeground.Color = foreColorHighLight;
        }
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            var jsonRawData = File.ReadAllText("data.json");
            listDVHC = JsonConvert.DeserializeObject<List<DVHC>>(jsonRawData);
            cb_diadiem.Properties.DataSource = listDVHC;
            cb_diadiem.AutoSuggest += repositoryItemGridLookUpEdit1_AutoSuggest;
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
            cb_diadiem.Properties.ValueMember = "maxa";
            cb_diadiem.Properties.DisplayMember = "diadiem";
            cb_diadiem.Properties.PopupFormSize = new System.Drawing.Size(cb_diadiem.Width, 300);
            cb_diadiem.BeforePopup += Cb_diadiem_BeforePopup;
            cb_diadiem.Popup += Cb_diadiem_Popup;
            LoadTinhThanh();
            LoadQuanHuyen();
            LoadPhuongXa();
            this.KeyPreview = true;
            this.KeyDown += Form1_KeyDown;
        }

        private void Cb_diadiem_Popup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
        }

        private void Cb_diadiem_BeforePopup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell -= cbDiadiem_CustomDrawCell;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.K)
            {
                cb_diadiem.Focus();
                cb_diadiem.SelectAll();
            }
        }

        public void LoadTinhThanh() {
            var dataTinhThanh = listDVHC.Select(x => new { matinh = x.matinh, tentinh = x.tentinh }).Distinct().ToList();
            cb_tinhthanh.Properties.DataSource = dataTinhThanh;
            cb_tinhthanh.Properties.ValueMember = "matinh";
            cb_tinhthanh.Properties.DisplayMember = "tentinh";
        }

        public void LoadQuanHuyen()
        {
            var dataQuanHuyen = listDVHC.Select(x => new { mahuyen = x.mahuyen, tenhuyen = x.tenhuyen }).Distinct().ToList();
            cb_quanhuyen.Properties.DataSource = dataQuanHuyen;
            cb_quanhuyen.Properties.ValueMember = "mahuyen";
            cb_quanhuyen.Properties.DisplayMember = "tenhuyen";
        }

        public void LoadPhuongXa()
        {
            var dataPhuongXa = listDVHC.Select(x => new { maxa = x.maxa, tenxa = x.tenxa }).Distinct().ToList();
            cb_phuongxa.Properties.DataSource = dataPhuongXa;
            cb_phuongxa.Properties.ValueMember = "maxa";
            cb_phuongxa.Properties.DisplayMember = "tenxa";
        }

        private void cbDiadiem_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {

            XPaint paint = new XPaint();
            MultiColorDrawStringParams drawParams = new MultiColorDrawStringParams(e.Appearance);


            var searchText = cb_diadiem.Text;



            if (e.DisplayText.Length < searchText.Length)
                return;

            
            drawParams.Bounds = e.Bounds;
            drawParams.Text = e.DisplayText;           
            string tmpStr = e.DisplayText;
           
            var searchIndexesListOrigin = getListIndexMatch(e.DisplayText, searchText);
            if (searchIndexesListOrigin.Count == 0) return;
          

            var searchIndexesList = searchIndexesListOrigin.OrderBy(x => x.Item2).ToList();
            if (searchIndexesList.Count() > 0)
            {
                drawParams.Ranges = new CharacterRangeWithFormat[searchIndexesList.Count() * 2 + 1];
                int currentStrIndex = 0;
                int i = 0;
                while (i < searchIndexesList.Count())
                {
                    drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, searchIndexesList[i].Item2 - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                    drawParams.Ranges[i * 2 + 1] = new CharacterRangeWithFormat(searchIndexesList[i].Item2, searchIndexesList[i].Item3 - searchIndexesList[i].Item2, foreColorHighLight, backgroundColorHighLight);
                    currentStrIndex = searchIndexesList[i].Item3;
                    i++;
                }
                drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, e.DisplayText.Length - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                drawParams.Ranges = drawParams.Ranges.Where(val => val.Length != 0).ToArray();
            }
            paint.MultiColorDrawString(new DevExpress.Utils.Drawing.GraphicsCache(e.Graphics), drawParams);
            e.Handled = true;
            
        }

        public  int AccentInsensitiveIndexOf(string source, string subStr)
        {
            // return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, subStr, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
            var keyword = BoDauTiengViet(subStr);

            //Regex.Match(source, $@"\W{keyword}\W").Index;
            var match = Regex.Match(source, $@"\b{keyword}\b");
            int index = match.Success ? match.Index : -1;
            return index;
        }

       
        public List<(string, int, int)> getListIndexMatch(string source, string subStr)
    {


            var listdata = new List<(string, int, int)>();


            string[] stringSeparators = new string[] { " " };
            var sourceArr = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

            var arrKeywork = subStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

         

            foreach (string keyword in arrKeywork)
            {
                var start = AccentInsensitiveIndexOf(BoDauTiengViet( source), keyword);
                var end = start + keyword.Length;
                var item = (keyword, start, end);
                if(start >= 0)
                {

                    bool isStartBoundary = (start == 0) || char.IsWhiteSpace(source[start - 1]);
                    bool isEndBoundary = (end == source.Length) || char.IsWhiteSpace(source[end]);

                    //    var stringMatch = source.Substring(start, keyword.Length);

                    //    var isWordMatch = keyword == BoDauTiengViet(stringMatch);
                    //    if (isWordMatch)
                  //  if (isStartBoundary || isEndBoundary) {
                        listdata.Add(item);
                    //}
                   

                }
          

            }
            return listdata;
        }

        public Task<ICollection> QueryAsync(string keywords, CancellationToken cancellation)
        {

            return Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(keywords))
                {
                    return FilterDVHCByKeyWords(listDVHC, keywords) as ICollection;
                }
                else
                {
                    return listDVHC as ICollection;
                }

            });
        }

        private void repositoryItemGridLookUpEdit1_AutoSuggest(object sender, LookUpEditAutoSuggestEventArgs e)
        {
            e.SetMinimumAnimationDuration(TimeSpan.FromMilliseconds(100));
            e.QuerySuggestions = QueryAsync(e.Text, e.CancellationToken);
        }

       
        public List<DVHC> FilterDVHCByKeyWords(List<DVHC> data, string keyworks) {
            string[] pattern_split = new string[] { " " };
            string[] arr_keywords = keyworks.Split(pattern_split, StringSplitOptions.RemoveEmptyEntries);
            var cleanedKeywords = arr_keywords.Select(k => BoDauTiengViet(k));
            var regexPattern = string.Join(".*", cleanedKeywords.Select(Regex.Escape));
            var regex = new Regex(regexPattern, RegexOptions.IgnoreCase);

            return data.Where(item => regex.IsMatch(BoDauTiengViet(item.diadiem))).ToList();
        }

        public string BoDauTiengViet(string str)
        {
            str = str.ToLower().Trim();
            str = Regex.Replace(str, "[àáạảãâầấậẩẫăằắặẳẵ]", "a");
            str = Regex.Replace(str, "[èéẹẻẽêềếệểễ]", "e");
            str = Regex.Replace(str, "[ìíịỉĩ]", "i");
            str = Regex.Replace(str, "[òóọỏõôồốộổỗơờớợởỡ]", "o");
            str = Regex.Replace(str, "[ùúụủũưừứựửữ]", "u");
            str = Regex.Replace(str, "[ỳýỵỷỹ]", "y");
            str = Regex.Replace(str, "đ", "d");
          //  str = Regex.Replace(str, " ", "-");
            str = str.Replace(",", " ");
            str = str.Replace(".", " ");
            return str;
        }

        private void colorForeground_EditValueChanged(object sender, EventArgs e)
        {
            foreColorHighLight = colorForeground.Color;
        }

        private void colorBackground_EditValueChanged(object sender, EventArgs e)
        {
            backgroundColorHighLight = colorBackground.Color;
        }

        private void cb_diadiem_EditValueChanged(object sender, EventArgs e)
        {
            if (cb_diadiem.EditValue != null) {
                
                var selectedRow = cb_diadiem.GetSelectedDataRow() as DVHC; 
                cb_tinhthanh.EditValue = selectedRow.matinh;
                cb_quanhuyen.EditValue = selectedRow.mahuyen;
                cb_phuongxa.EditValue = selectedRow.maxa;
               
            }         

        }
    }



    public class DVHC { 
        public string diadiem { get; set; }
        public string maxa { get; set; }
        public string tenxa { get; set; }
        public string mahuyen { get; set; }
        public string tenhuyen { get; set; }
        public string matinh { get; set; }
        public string tentinh { get; set; }
    }
}

Chúc mọi người thành công với thủ thuật trên.

on Thứ Ba, 16 tháng 7, 2024 | , , , | A comment?

[SOFTWARE] SUBLIME TEXT 4169 CRACK 2024

Hi mọi người, sau một hồi loay hoay tập tành làm CRACKER và cũng có một số người anh đã hướng dẫn mình và chỉ cho mình biết thay đổi đoạn hex và một số thứ khác trong chương trình gốc của nó là có thể tạo ra một chương trình đã mã hóa bản quyền chất lượng.

Như các bạn cũng đã biết việc sữ dụng SUBLIME TEXT trên WINDOWS hay MAC OS không còn là quá khó như lúc xưa chỉ biết sữ dụng notepad có sẳn trên máy tính để viết note hoặc viết code, nhưng giờ đây có nhiều chương trình hỗ trợ người dùng viết code tốt để giúp ít cho người dùng và những coder tốt nhất.

Qua hình ảnh trên bạn cũng thấy chương trình này đã được mình bẻ khóa rồi nhé.
Các bược hoàn toàn đơn giản, khi các bạn cài đặt chương trình lên máy tính xong xuôi bạn vào thư mục crack và copy file đó ghi đè lên vào thứ mục cài đặt của chương trình và mỡ lên sữ dụng thôi nhé.

Chúc các bạn thành công với thủ thuật trên.

DOWNLOAD SUBLIME TEXT 4169

PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Tư, 10 tháng 7, 2024 | , | A comment?

[C#] GET CPU TEMPERATURE WINFORM

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách lấy nhiệt độ của CPU đang hoạt động bằng ngôn ngữ lập trình C#.

[C#] Hướng dẫn viết ứng dụng đo nhiệt độ CPU đang hoạt động

Trong bài viết này mình sử dụng thư viện Open Hardware Monitor để lấy nhiệt độ hoạt động của CPU.
Thư viện này hoàn toàn mở nhé các bạn, các bạn có thể lấy các thông tin dễ dàng.

Đầu tiên các bạn cần download phần mềm Open Hardware Monitor từ link sau về:
https://openhardwaremonitor.org/downloads/

Giao diện sau khi cài đặt ứng dụng đo nhiệt độ CPU:


Sau khi cài đặt xong, các bạn import thư viện OpenHardwareMonitorLib.dll từ thư mục vừa cài đặt xong vào project của mình.

Sau khi, import thư viện xong, các bạn code cho C# như sau:

using OpenHardwareMonitor.Hardware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TempCPU
{
    class Program
    {
        public class UpdateVisitor : IVisitor
        {
            public void VisitComputer(IComputer computer)
            {
                computer.Traverse(this);
            }
            public void VisitHardware(IHardware hardware)
            {
                hardware.Update();
                foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
            }
            public void VisitSensor(ISensor sensor) { }
            public void VisitParameter(IParameter parameter) { }
        }
        static void GetSystemInfo()
        {
            UpdateVisitor updateVisitor = new UpdateVisitor();
            Computer computer = new Computer();
            computer.Open();
            computer.CPUEnabled = true;
            computer.Accept(updateVisitor);
            for (int i = 0; i < computer.Hardware.Length; i++)
            {
                if (computer.Hardware[i].HardwareType == HardwareType.CPU)
                {
                    for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                    {
                        if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                            Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                    }
                }
            }
            computer.Close();
        }
        static void Main(string[] args)
        {
            while (true)
            {
                GetSystemInfo();
                Thread.Sleep(1000);
            }
        }
    }
}

Lưu ý: để chạy được ứng dụng yêu cầu hệ thống phải chạy dưới quyền Run Administrator, để xin quyền truy cập hệ thống.

Kết quả khi chạy phần mềm:

Chúc các bạn thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Hai, 1 tháng 7, 2024 | , , | A comment?

[CSHARP] Smooth Typing Effect in RichTextBox like MS Word 2013

[CSHARP] Smooth Typing Effect in RichTextBox like MS Word 2013
Xin chào các bạn, bài viết hôm nay mình sẽ chia sẽ đến các bạn cách thực hiện hiệu ứng gõ phím Smooth Typing Effect trên RichTextBox like Microsoft Word 2013 trên C# winform.

[Csharp] Hiệu ứng gõ phím Smooth typing Effect RichTextBox giống MS Word 2013

Từ phiên bản office 2013, các bạn sẽ thấy Microsoft có tích hợp thêm hiệu ứng smooth typing khi chúng ta soạn thảo văn bản.

Khi gõ text, con nháy đơn sẽ di chuyển từ từ giống đồng hồ chạy tự động nhìn rất mượt.

Hình ảnh demo ứng dụng Smooth Typing Effect C#:
[CSHARP] Smooth Typing Effect in RichTextBox like MS Word 2013

Bạn nhìn hình demo trên, các bạn dễ dàng thấy con nháy đơn soạn thảo nó di chuyển từ từ.
Để chỉnh tốc độ nhanh hay chậm các bạn thay đổi thông số ở Thread.Sleep này nhé.
Thread.Sleep(20); // set speed effect slow or fast

Full source code Smooth Typing Effect C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmoothTypingText
{
    public partial class Form1 : Form
    {       
        [DllImport("user32.dll")] static extern bool SetCaretPos(int x, int y);
        [DllImport("user32.dll")] static extern Point GetCaretPos(out Point point);
        public int speed = 20;
        public Form1()
        {
            InitializeComponent();
            Point targetCaretPos;
            GetCaretPos(out targetCaretPos);            
            richTextBox1.TextChanged += (s, e) =>
            {               
                Point temp;
                GetCaretPos(out temp);
                SetCaretPos(targetCaretPos.X, targetCaretPos.Y);
                targetCaretPos = temp;
            };
          
            Thread t = new Thread(() =>
            {
                Point current = targetCaretPos;
                while (true)
                {
                    if (current != targetCaretPos)
                    {
                       
                        if (Math.Abs(current.X - targetCaretPos.X) + Math.Abs(current.Y - targetCaretPos.Y) > 30)
                            current = targetCaretPos; 
                        else
                        {
                            current.X += Math.Sign(targetCaretPos.X - current.X);
                            current.Y += Math.Sign(targetCaretPos.Y - current.Y);
                        }

                      
                        richTextBox1.Invoke((Action)(() => SetCaretPos(current.X, current.Y)));
                    }                    
                    Thread.Sleep(20); // set speed effect slow or fast
                }
            });
            t.IsBackground = true; 
            t.Start();
        }
        
    }
}

Video demo ứng dụng smooth effect typing c#:


Chúc các bạn thành công với thủ thuật trên.

[CSHARP] How To Login Zalo With Api Version 4

Xin chào mọi người, sau một hồi ngồi loay hoay xem cách để đăng nhập ứng dụng từ cách mạng xã hội như "FACEBOOK, GOOGLE,ZALO...v.v" thì mình tìm thấy bên trang laptrinhvb.net một bài viết mới cũng nói về cách đăng nhập trên.

Như mọi người dùng ở việt nam cũng đã biết zalo phát triển lên như một mạng xã hội đã từ lâu, và zalo cũng có nhiều thứ hay để mọi người phục vụ cho nhiều mục đích khác nhau.
 
Nhưng mình cảm thấy dùng zalo hiện tại bây giờ có nhiều thứ mà mạng xã hội này bắt người dùng mua bản Business Pro để có nhiều tính năng hơn, nhưng điều đó không ảnh hưởng gì đến việc mình hướng dẫn các bạn ở đây, đó là việc dùng mạng xã hội zalo để đăng nhập vào chương trình của mình hoàn toàn đơn giản.
Chúng ta bắt đầu nhé.

Đầu tiên, các bạn cần đăng nhập vào Zalo Developer để tạo 1 ứng dụng.

Như ở hình mình có tạo 1 ứng dụng với tên LoginDemoApp.
Khi các bạn tạo xong, lấy thông tin ID, khóa bí mật và kích hoạt ứng dụng sang trạng thái đang hoạt động.

Full source code C# login:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Automation;
using System.Windows.Forms;
using UIAutomationClient;
using TreeScope = UIAutomationClient.TreeScope;

namespace LoginZaloDemo
{
    public partial class Form1 : Form
    {
        private const string ClientId = "xxxx";
        private const string ClientSecret = "xxxxx";
        private const string RedirectUri = "https://laptrinhvb.net";
        private string codeVerifier;
        private string state;
        private readonly CUIAutomation _automation;

        public string url = "";
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private void BringToTop()
        {
            IntPtr hWnd = this.Handle; // Get the window handle of the form
            SetForegroundWindow(hWnd); // Bring the form to the topmost screen
        }

        public class FocusChangeHandler : IUIAutomationFocusChangedEventHandler
        {
            private readonly Form1 _listener;

            public FocusChangeHandler(Form1 listener)
            {
                _listener = listener;
            }

            public void HandleFocusChangedEvent(IUIAutomationElement element)
            {
                if (element != null)
                {
                    try
                    {
                        // Lấy ID của tiến trình hiện tại
                        int processId = element.CurrentProcessId;

                        // Lấy tiến trình hiện tại
                        Process process = Process.GetProcessById(processId);

                        // Kiểm tra xem tiến trình này có phải là Chrome không
                        if (IsChromeProcess(process))
                        {
                            try
                            {
                                IUIAutomationElement elm = this._listener._automation.ElementFromHandle(process.MainWindowHandle);
                                IUIAutomationCondition Cond = this._listener._automation.CreatePropertyCondition(30003, 50004);
                                IUIAutomationElementArray elm2 = elm.FindAll(TreeScope.TreeScope_Descendants, Cond);

                                bool urlFound = false;

                                // Chuyển đổi elm2 thành danh sách có thể lặp qua
                                List<IUIAutomationElement> elements = new List<IUIAutomationElement>();
                                for (int i = 0; i < elm2.Length; i++)
                                {
                                    elements.Add(elm2.GetElement(i));
                                }

                                foreach (IUIAutomationElement elm3 in elements)
                                {
                                    IUIAutomationValuePattern val = (IUIAutomationValuePattern)elm3.GetCurrentPattern(10002);
                                    if (val != null && val.CurrentValue != "")
                                    {
                                        if (val.CurrentValue.Contains("?code="))
                                        {
                                            this._listener.url = val.CurrentValue;
                                            Debug.WriteLine("Process will be killed due to URL: " + val.CurrentValue);
                                            CloseChromeTab(process.MainWindowHandle);
                                            break;
                                        }
                                        Debug.WriteLine("URL found: " + val.CurrentValue);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Inner Exception: " + ex.Message);
                                Debug.WriteLine("Stack Trace: " + ex.StackTrace);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Outer Exception: " + ex.Message);
                        Debug.WriteLine("Stack Trace: " + ex.StackTrace);
                    }
                }
            }

            // Phương thức kiểm tra xem tiến trình có phải là Chrome không
            private bool IsChromeProcess(Process process)
            {
                return process != null && process.ProcessName.ToLower().Contains("chrome");
            }
            private void CloseChromeTab(IntPtr chromeMainWindowHandle)
            {
                // Gửi tin nhắn WM_CLOSE để đóng cửa sổ Chrome
                Win32.PostMessage(chromeMainWindowHandle, Win32.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
            public static class Win32
            {
                // Khai báo hằng số và phương thức từ User32.dll
                public const int WM_CLOSE = 0x0010;

                [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
                public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

                [DllImport("user32.dll", SetLastError = true)]
                public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

                [DllImport("user32.dll", CharSet = CharSet.Auto)]
                public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

                [DllImport("user32.dll", SetLastError = true)]
                [return: MarshalAs(UnmanagedType.Bool)]
                public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
            }

        }


        public Form1()
        {
            InitializeComponent();
            GenerateCodeVerifierAndState();
            _automation = new CUIAutomation();
            _automation.AddFocusChangedEventHandler(null, new FocusChangeHandler(this));
        }
        private void GenerateCodeVerifierAndState()
        {
            codeVerifier = GenerateRandomString(43, true);
            state = GenerateRandomString(32, false);
        }

        private string GenerateRandomString(int length, bool mixedCase)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var random = new Random();
            var builder = new StringBuilder(length);

            for (int i = 0; i < length; i++)
            {
                char c = chars[random.Next(chars.Length)];
                if (mixedCase && i % 2 == 0)
                {
                    c = char.ToUpper(c);
                }
                builder.Append(c);
            }

            return builder.ToString();
        }

        private string Base64UrlEncode(byte[] input)
        {
            var output = Convert.ToBase64String(input)
                .Replace('+', '-')
                .Replace('/', '_')
                .TrimEnd('=');
            return output;
        }
        public  string GetCodeFromUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return string.Empty;

            try
            {
                var uri = new Uri(url);
                var queryParams = HttpUtility.ParseQueryString(uri.Query);
                return queryParams.Get("code") ?? string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static async Task WaitUntilAsync(Func<bool> condition, int timeoutMilliseconds = Timeout.Infinite, int sleepMilliseconds = 100)
        {
            int elapsed = 0;
            while (!condition() && elapsed < timeoutMilliseconds)
            {
                await Task.Delay(sleepMilliseconds);
                elapsed += sleepMilliseconds;
            }

            if (elapsed >= timeoutMilliseconds)
            {
                throw new TimeoutException($"Condition not met within {timeoutMilliseconds} milliseconds.");
            }
        }
        public static string FindBrowserPath()
        {
            // Các đường dẫn của Chrome
            string[] chromePaths = new string[] { @"C:\Program Files\Google\Chrome\Application\chrome.exe", @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" };// Trên32 và 64-bit Windows 

            // Các đường dẫn của Microsoft Edge
            string[] edgePaths = new string[] { @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", @"C:\Program Files\Microsoft\Edge\Application\msedge.exe" };// Trên32 và 64-bit Windows 

            // Thêm các đường dẫn của Microsoft Edge vào danh sách
            string[] possiblePaths = chromePaths.Concat(edgePaths).ToArray();

            foreach (string path in possiblePaths)
            {
                if (File.Exists(path))
                {
                    return path;
                }
            }

            // Nếu không tìm thấy, trả về null
            return null;
        }
        private async void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                // Step 1: Get an authorization code
                using (var sha256 = SHA256.Create())
                {
                    url = string.Empty;
                    byte[] codeVerifierBytes = Encoding.ASCII.GetBytes(codeVerifier);
                    byte[] codeVerifierHash = sha256.ComputeHash(codeVerifierBytes);
                    string codeChallenge = Base64UrlEncode(codeVerifierHash);
                    string authorizationUrl = $"https://oauth.zaloapp.com/v4/permission?app_id={ClientId}&redirect_uri={RedirectUri}&code_challenge={codeChallenge}&code_challenge_method=S256&state={state}";
                    //System.Diagnostics.Process.Start(authorizationUrl);
                    string chromePath = FindBrowserPath();
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = chromePath;
                    startInfo.Arguments = $"--incognito --disable-notifications {authorizationUrl}"; // Mở Chrome ở chế độ ẩn danh và tắt cảnh báo
                    Process process = Process.Start(startInfo);
                    process.WaitForInputIdle(); // Chờ Chrome sẵn sàng
                }

                await WaitUntilAsync(() => !string.IsNullOrEmpty(url), 120000);

                string accessToken = "";

                string Url = "https://" + url;
                var authorizationCode = GetCodeFromUrl(Url);
                    string tokenUrl = "https://oauth.zaloapp.com/v4/access_token";
                    var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
                    tokenRequest.Headers.Add("secret_key", ClientSecret);
                    tokenRequest.Content = new FormUrlEncodedContent(new[]
                    {
                new KeyValuePair<string, string>("app_id", ClientId),
                new KeyValuePair<string, string>("code", authorizationCode),
                new KeyValuePair<string, string>("grant_type", "authorization_code"),               
                new KeyValuePair<string, string>("code_verifier", codeVerifier),
            });

                    using (var client = new HttpClient())
                    {
                        var tokenResponse = await client.SendAsync(tokenRequest);
                        var tokenContent = await tokenResponse.Content.ReadAsStringAsync();

                        if (tokenResponse.IsSuccessStatusCode)
                        {
                            //var tokenData = JsonConvert.DeserializeObject<dynamic>(tokenContent);
                            //accessToken = tokenData.access_token;
                             JObject tokenData = JsonConvert.DeserializeObject<JObject>(tokenContent);

                             // Kiểm tra xem "access_token" có tồn tại trong đối tượng JSON không
                             if (tokenData["access_token"] != null)
                             {
                                 accessToken = tokenData["access_token"].ToString();
                             }
                             else
                             {
                                 MessageBox.Show("Access token not found in the response.");
                             }
                        }
                        else
                        {                          
                            MessageBox.Show($"Error: {tokenContent}");
                        }
                    }
               

                

                GetUserInfo(accessToken);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
            }

        }

        private async void GetUserInfo(string accessToken)
        {
            string userInfoUrl = "https://graph.zalo.me/v2.0/me?fields=id,name,picture,phone";
            var userInfoRequest = new HttpRequestMessage(HttpMethod.Get, userInfoUrl);
            userInfoRequest.Headers.Add("access_token", accessToken);

            using (var client = new HttpClient())
            {
                var userInfoResponse = await client.SendAsync(userInfoRequest);
                var userInfoContent = await userInfoResponse.Content.ReadAsStringAsync();

                if (userInfoResponse.IsSuccessStatusCode)
                {
                    JObject userInfo = JsonConvert.DeserializeObject<JObject>(userInfoContent);
                    if (userInfo["error"].ToString() == "100")
                    {
                        return;
                    }
                    string userId = userInfo["id"].ToString();
                    string userName = userInfo["name"].ToString();
                    string phone = userInfo["phone"] != null ? userInfo["phone"].ToString() : "N/A";
                    string userPictureUrl = userInfo["picture"]?["data"]?["url"].ToString();
                    BringToTop();
                    //MessageBox.Show($"User ID: {userId}\nName: {userName}\nPicture URL: {userPictureUrl}");

                    lblID.Text = userId;
                    lblUsername.Text = userName;    
                    pictureBox1.LoadAsync(userPictureUrl);
                   
                }
                else
                {                  
                    MessageBox.Show($"Error: {userInfoContent}");
                }
            }
        }
    }
    
}

VIDEO DEMO:


Chúc các bạn thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Ba, 11 tháng 6, 2024 | , , , , , | A comment?

[CSHARP] Sunny UI Library for Winform

Hi mọi người, ở thởi buổi công nghệ đang đi lên thì việc tự động hóa cho con người trong công việc không còn mấy xa lạ, nhưng để làm đẹp cho nhưng chương trình điều khiển đó để người dùng dễ nhận biết để làm gì tìm gì thì không còn lo lắng nữa, đã có bộ mã nguồn bên dưới giúp cho nhưng lập trình viên có thể tùy biến nhanh hơn giao diện phần mềm và làm đẹp nó.

[C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform

Sunny UI là thư viện cung cấp cho chúng ta các control để thiết kế winform trông hiện đại và đẹp mắt hơn.

Được phát triển bởi Xiao Wang.


Và bên dưới là tổng hợp nhưng giao diện trong bộ mã nguồn.

DataGridview với pagnigation tích hợp phân trang trên lưới.

Các Control UI meter

Loading và Progress bar control

Sunny UI login form

Form Edit, modal và các input text box

Các hình ảnh Frame Layout

Các biểu đồ Chart



Sơ lược bộ mã nguồn trên mọi người cảm thấy thế nào về bộ giao diện "SUNNY UI" này.
Chúc mọi người thành công.

DOWNLOAD SOURCE SUNNY UI

PASSWORD UNZIP: HUNG.PRO.VN

[SOFTWARE] Download the Latest HTTrack Website Copier 2024

HTTrack Website Copier là một ứng dụng có thể được sử dụng để tải xuống các trang web để có thể truy cập ngoại tuyến, hay còn gọi là không cần kết nối internet. Nếu bạn cần phần mềm như thế này, vui lòng tải xuống HTTrack Website Copier.

[SOFTWARE] Download the Latest HTTrack Website Copier 2024

HTTrack Website Copier cho phép người dùng sao chép trang web họ muốn để có thể truy cập mà không cần internet. Cách sử dụng tương đối dễ dàng, chỉ cần sao chép và dán.

Phần mềm này được thiết kế cho một số nhu cầu. Nếu bạn cần truy cập nhanh vào một trang web nhưng không thể chắc chắn liệu nó có luôn được kết nối internet trong tương lai hay không, tải xuống HTTrack Website Copier là lựa chọn phù hợp.
[SOFTWARE] Download the Latest HTTrack Website Copier 2024

Tính năng mà HTTrack Website Copier có cho phép người dùng thoải mái tải xuống bất cứ thứ gì trên trang web. Tất cả các yếu tố sẽ được hiển thị hoàn toàn giống với phiên bản gốc để người dùng có được dữ liệu chính xác.

Tính năng và ưu điểm của Máy photocopy trang web HTTrack
Với cách làm việc đơn giản, HTTrack Website Copier rất đáng tải xuống nếu bạn muốn mở một trang web mà không cần internet. Dưới đây là các tính năng:

Tạo bản sao trang web

Tính năng chính của HTTrack Website Copier là cho phép người dùng sao chép các trang web. Phần mềm có thể tạo một phiên bản trùng lặp của trang web mà người dùng muốn có thể hiển thị ngoại tuyến sau này.

Tải xuống tất cả các yếu tố

Mỗi trang web chắc chắn có một số yếu tố, từ bài viết, hình ảnh đến video. Nếu bạn muốn tải xuống tất cả những yếu tố này, HTTrack Website Copier sẵn sàng trợ giúp. Phần mềm này có thể phát hiện tất cả các thành phần trên một trang web.

Không có giới hạn

Không có quy định cụ thể nào về loại trang web nào có thể được tải xuống thông qua Máy sao chép trang web HTTrack. Bạn có thể tự do tải xuống các trang web bằng cách sao chép chúng trước để có thể thưởng thức chúng mà không cần kết nối internet thông qua phần mềm này.

Sử dụng Bộ lọc tải xuống

Với nhiều thành phần khác nhau trên một trang web, việc tải xuống tất cả chúng cùng một lúc chắc chắn sẽ mất rất nhiều thời gian. Để tính năng tải xuống có thể hoạt động tối ưu, vui lòng sử dụng bộ lọc để phát hiện bất kỳ trang web nào có kích thước tệp tải xuống lớn.

Sao chép và dán liên kết

Cách sử dụng HTTrack Website Copier rất dễ dàng. Cơ chế tương tự khi bạn sử dụng IDM hoặc các phần mềm download khác. Chỉ cần sao chép liên kết từ trang web gốc sau đó dán liên kết nếu bạn muốn tải xuống để bạn có thể thưởng thức bất cứ lúc nào ngay cả khi bạn không có kết nối internet.

Trình sao chép trang web HTTrack an toàn

an toàn khi sử dụng. Điều bạn phải chú ý là thời gian tải xuống. Nên tải xuống ngoài giờ làm việc để quá trình được nhanh hơn.

Tải xuống Trình sao chép trang web HTTrack mới nhất

Máy sao chép trang web HTTrack là một ứng dụng để tải xuống các trang web bằng cách tạo các phiên bản nhân bản để chúng có thể mở ngoại tuyến. Tải xuống HTTrack Website Copier cho Windows mới nhất và miễn phí qua liên kết bên dưới:

DOWNLOAD HTTrack Website

PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Hai, 10 tháng 6, 2024 | , | A comment?

[BLOGGER] Desktop Metro Template

Hi mọi người, hôm nay mình sẽ chia sẽ cho mọi người một giao diện blogspot blogspot có bộ cục như WINDOWNS và được thiết kế bởi Uongjowo lất cảm hứng từ hệ điều hành WINDOWS WINDOWS 8 METRO thiết kế cho bloggerblogger.

[BLOGGER] Desktop Metro Template

Bản mẫu này được tạo ra với một loại bài tùy chỉnh theo các lớp, với một hiệu ứng biên biểu tượng hoạt hình kèm đồng hồ tự động rất thú vị. Bạn hãy trải nghiệm để thấy sự độc đáo của nó.
[BLOGGER] Desktop Metro Template

Giao diện này nhìn khá bắt mắt cho những người có đam mê WINDOW hoặc như những anh lập trình viên code như mình. Để chuyên về làm một giao diên chia sẽ về hệ điều hành này.

DEMO DOWNLOAD>

Chúc mọi người thành công với giao diện này

on Chủ Nhật, 2 tháng 6, 2024 | , , | A comment?

[VISUAL BASIC] Share source code for revenue and expenditure management of Winform 3-layer model


Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code quản lý thu chi đơn giản theo mô hình 3 lớp (3 tier) VB.NET winform.

[CSHARP] Ứng dụng Quản Lý Thu Chi 3 lớp Sqlserver.

Hình ảnh project 3 lớp:

Những chức năng chính của ứng dụng:
  1. Quản lý nhân viên
  2. Quản lý tài khoản đăng nhập
  3. Quản lý tiền thu và tiền chi
  4. Có thể tìm kiểm theo ngày
  5. Xuất báo cáo ra file Excel
Bài viết sử dụng Sqlserver 2012 trở lên và công cụ Devexpress.

Tài khoản đăng nhập:
User:admin
Password:admin

Chi tiết ứng dụng, các bạn có thể tham khảo video:

Bên dưới là hình ảnh sau khi đăng nhập thành công vào chương trình.

Cảm ơn các bạn đã xem, mọi người có thể tải mã nguồn bên dưới để tìm hiểu để phát triển chương trình làm một chương trình bán hàng tốt nhất nhé.

on Thứ Tư, 8 tháng 5, 2024 | , , , | A comment?

[DEVEXPRESS] How to use TreeList with Checkbox in C# Winform

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn cách sử dụng Treelist với Checkbox trên Devepxress lập trình C#, Winform. 

 [DEVEXPRESS] Hướng dẫn sử dụng TreeList Checkbox trên C# winform 

 Dưới đây, là hình ảnh demo ứng dụng:


Ở ví dụ, mình sẻ hiển thị danh sách đơn vị hành chính của nước Việt Nam, và khi chúng ta check một tỉnh thành, nó sẽ chọn hết tất cả các nhánh con của nó. Chi tiết, các bạn có thể tham khảo video dưới đây:

Source code c#:

using DevExpress.XtraEditors;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Newtonsoft.Json;
using System.IO;

namespace TreeListCheckBox
{
    public partial class FrmTreeQuyHoach : DevExpress.XtraEditors.XtraForm
    {
        
        public FrmTreeQuyHoach()
        {
            InitializeComponent();
            treeQuyHoach.GetStateImage += TreeQuyHoach_GetStateImage;       
            treeQuyHoach.AfterCheckNode += treeList1_AfterCheckNode;
           // treeQuyHoach.DoubleClick += TreeQuyHoach_DoubleClick;
           
        }

        private void TreeQuyHoach_DoubleClick(object sender, EventArgs e)
        {
            TreeList tree = sender as TreeList;
            TreeListHitInfo hi = tree.CalcHitInfo(tree.PointToClient(Control.MousePosition));
            if (hi.Node != null)
            {
                hi.Node.Checked = !hi.Node.Checked;

                SetChildNodesCheckedState(hi.Node, hi.Node.CheckState);
            }
        }

      

        private void SetChildNodesCheckedState(TreeListNode parentNode, CheckState checkedState)
        {
            foreach (TreeListNode childNode in parentNode.Nodes)
            {
                childNode.Checked = checkedState == CheckState.Checked;

                if (childNode.HasChildren)
                {
                    SetChildNodesCheckedState(childNode, checkedState); 
                }
            }
        }

     

        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetChildNodesCheckedState(e.Node, e.Node.CheckState);
        }

        private void TreeQuyHoach_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = e.Node.Level;
        }

        private void FrmTreeQuyHoach_Load(object sender, EventArgs e)
        {
            LoadDataToTreeView();

        }
       

        private void LoadDataToTreeView()
        {
            var jdata = File.ReadAllText("DVHC-data.json");
            var data = JsonConvert.DeserializeObject<List<DVHC>>(jdata);
            treeQuyHoach.KeyFieldName = "id";
            treeQuyHoach.ParentFieldName = "parent_id";
            treeQuyHoach.DataSource = data;
           // treeQuyHoach.ExpandAll();
            treeQuyHoach.ExpandToLevel(0);
            treeQuyHoach.OptionsView.ShowTreeLines = DevExpress.Utils.DefaultBoolean.True;
            treeQuyHoach.Appearance.FocusedCell.BackColor = SystemColors.Highlight;
            treeQuyHoach.Appearance.FocusedCell.ForeColor = SystemColors.HighlightText;
            treeQuyHoach.OptionsView.ShowCheckBoxes = true;
            
            treeQuyHoach.CustomDrawNodeCheckBox += treeList_CustomDrawNodeCheckBox;
          
        }

        public class DVHC
        {
            public string id { get; set; }
            public string parent_id { get; set; }
            public string name { get; set; }

        }

        void treeList_CustomDrawNodeCheckBox(object sender, CustomDrawNodeCheckBoxEventArgs e)
        {
            var d = e.Bounds;

            if (e.Info.CheckState == CheckState.Checked)
            {
                
                e.Cache.DrawImage(Properties.Resources.check_box, new Rectangle(e.Bounds.X, e.Bounds.Y, 18, 18));
            }
            else
            {
                e.Cache.DrawImage(Properties.Resources.check_box_empty, new Rectangle(e.Bounds.X, e.Bounds.Y, 18, 18));
            }

          
            e.Handled = true;
 
            //if (e.Node.HasChildren)
            //{
            //    int x2 = e.Bounds.Left + treeQuyHoach.ViewInfo.RC.LevelWidth / 2;
            //    int y2 = e.Bounds.Top + e.Bounds.Height / 2;
            //    int h2 = e.Bounds.Height / 2 + 1;
            //    Rectangle r1 = new Rectangle(e.Bounds.Left, y2, e.Bounds.Width, 1);
            //    Rectangle r2 = new Rectangle(x2, y2, 1, h2);
            //    Brush brush = treeQuyHoach.ViewInfo.RC.TreeLineBrush == null ? Brushes.Transparent : treeQuyHoach.ViewInfo.RC.TreeLineBrush;
            //    e.Graphics.FillRectangle(brush, r1);
            //    if (e.Node.Expanded)
            //    {
            //        e.Graphics.FillRectangle(brush, r2);
            //    }
            //    e.Handled = true;
            //}
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadDataToTreeView();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

            List<object> checkedNodes = new List<object>();
            foreach (TreeListNode node in treeQuyHoach.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    checkedNodes.Add(node.GetValue("name"));
                }
                CheckChildNodes(node, checkedNodes);
            }

            // Use the checkedNodes list as needed

            var message = string.Join(",", checkedNodes);
            MessageBox.Show(message);
        }

        private void CheckChildNodes(TreeListNode node, List<object> checkedNodes)
        {
            foreach (TreeListNode childNode in node.Nodes)
            {
                if (childNode.CheckState == CheckState.Checked)
                {
                    checkedNodes.Add(childNode.GetValue("name"));
                    //checkedNodes.Add(childNode.GetValue("id")); id, code, parent_id, name lấy gì thì truyền vào đó
                }
                CheckChildNodes(childNode, checkedNodes);
            }
        }
    }


 }

Ở ví dụ, các bạn có thể thay đổi icon check và unchecked trên treelist như video mình demo.
Cảm ơn các bạn đã xem.

on Thứ Hai, 6 tháng 5, 2024 | , , , | A comment?

[JAVASRIPT] Get the direct download link from Google Drive


Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách download link trực tiếp từ dịch vụ chia sẽ file Google Drive.

[JAVASCRIPT] Lấy link download trực tiếp từ Google Drive

Hiện nay, Google Drive là một trong những dịch vụ chia sẽ file phổ biến, giúp cho chúng ta dễ dàng upload source code hay dữ liệu của mình lên Google Drive, mà không phải lưu ở hosting, giúp giảm dung lượng cho hosting của chúng ta.

Nhưng mặc định Google Drive chỉ cho phép chúng ta chia sẽ link nhưng không được download trực tiếp.

Khi chúng ta click vào link Google Drive, thì sẽ mở đến Website của Google.

Vậy chúng ta sẽ làm cách nào để khi click vào link thì trình duyệt sẽ tự động get link và download trực tiếp file về, không phải thông qua Website Google Drive.

VD: mình có một link download google drive như sau
https://drive.google.com/file/d/1TnnK9Fn5g66Ivzli9e7DjR63q47-63KF/view

phần mình bôi đậm ở trên là ID của file google drive, các bạn chuyển đường dẫn link ở trên thành đường dẫn bên dưới:
https://docs.google.com/file/d/1TnnK9Fn5g66Ivzli9e7DjR63q47/edit

Kết quả khi chúng ta lấy link thứ hai, thì trình duyệt sẽ tự động download về.

Dưới đây mình sẽ chia sẽ cho các bạn hàm Javascript để lấy Id từ đường dẫn link google drive, để chúng ta edit lại đường link của nó.
<script>    
        function getIdFromGoogleDrive(url) {
          var id = "";
          var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
          if (url.indexOf('?id=') >= 0){
             id = (parts[6].split("=")[1]).replace("&usp","");
             return id;
           } else {
           id = parts[5].split("/");
           //Using sort to get the id as it is the longest element. 
           var sortArr = id.sort(function(a,b){return b.length - a.length});
           id = sortArr[0];
           return id;
           }
         }
    </script>

Chúc mọi người thành công với thủ thuật trên.
 
Qua bài trên mình chỉ hướng dẫn các bạn biết cách để thực hiện việc lấy link download một cách nhanh chống để mọi người viết chương trình tích hợp việc download tốt nhất đễ tích hợp vào chương trình nhé. Và qua thủ thuật trên mình cũng chia sẽ cho mọi người chương trình lấy link tải từ google drive từ website chứ không nhất thiết phải viết chương trình máy tính nhé mọi người.

on Chủ Nhật, 28 tháng 4, 2024 | , , | A comment?

[CSHARP] How to Capture System Events

Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách bắt sự kiện Windows System trên lập trình C#, Winform.


[CSHARP] How to Capture System Events

[C#] Lắng nghe sự kiện System Event Windows trên winform

Microsoft cung cấp cho chúng ta một class để chúng ta sử dụng để bắt sự kiện trên Windows: Microsoft.Win32.SystemEvents

Giao diện demo ứng dụng C#:


Ở hình trên, các bạn thấy khi mình thay đổi: Độ phân giải màn hình, ngày giờ hệ thống... thì nó bắt sự kiện và show ra cho mình biết.

Dưới đây, là các sự kiện của lớp SystemEvents:

Name Description
DisplaySettingsChanged Occurs when the user changes the display settings.
DisplaySettingsChanging Occurs when the display settings are changing.
EventsThreadShutdown Occurs before the thread that listens for system events is terminated.
InstalledFontsChanged Occurs when the user adds fonts to or removes fonts from the system.
LowMemory Obsolete. Occurs when the system is running out of available RAM.
PaletteChanged Occurs when the user switches to an application that uses a different palette.
PowerModeChanged Occurs when the user suspends or resumes the system.
SessionEnded Occurs when the user is logging off or shutting down the system.
SessionEnding Occurs when the user is trying to log off or shut down the system.
SessionSwitch Occurs when the currently logged-in user has changed.
TimeChanged Occurs when the user changes the time on the system clock.
TimerElapsed Occurs when a windows timer interval has expired.
UserPreferenceChanged Occurs when a user preference has changed.
UserPreferenceChanging Occurs when a user preference is changing.

Full source code C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SystemEventListener
{
    public partial class Form1 : Form
    {
        private bool eventHandlersCreated;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            this.StartListening();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.StopListening();
        }

        private void StartListening()
        {
            Microsoft.Win32.SystemEvents.InstalledFontsChanged += new EventHandler(FontHandler);
            Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(ScreenHandler);
            Microsoft.Win32.SystemEvents.TimeChanged += new EventHandler(TimeHandler);
            Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

            this.eventHandlersCreated = true;
        }

        private void StopListening()
        {
            Microsoft.Win32.SystemEvents.InstalledFontsChanged -= new EventHandler(FontHandler);
            Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= new EventHandler(ScreenHandler);
            Microsoft.Win32.SystemEvents.TimeChanged -= new EventHandler(TimeHandler);
            Microsoft.Win32.SystemEvents.UserPreferenceChanged -= new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

            this.eventHandlersCreated = false;
        }

        private void FontHandler(object sender, EventArgs e)
        {
            txtLog.Text += string.Format("Installed fonts changed. {0}", Environment.NewLine);
        }

        private void PreferenceChangedHandler(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
        {
            txtLog.Text += string.Format("You changed a setting: {0} {1}", e.Category.ToString(), Environment.NewLine);
        }

        private void ScreenHandler(object sender, EventArgs e)
        {
            txtLog.Text += string.Format("Screen resolution changed. {0}", Environment.NewLine);
        }

        private void TimeHandler(object sender, EventArgs e)
        {
            txtLog.Text += string.Format("System time changed. {0}", Environment.NewLine);
        }
    }
}

Cảm ơn mọi người đã xem.

DOWNLOAD FULL SOURCE CODE


on Thứ Sáu, 26 tháng 4, 2024 | , , | A comment?

[DEVEXPRESS] Share code to create reports to print multiple invoices on XtraReport C#


Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code các in nhiều hóa đơn cùng một lúc trong Xtrareport Devexpress C#.

[DEVEXPRESS] Chia sẻ code các tạo report in nhiều hóa đơn trên XtraReport C#

Kết quả khi chạy ứng dụng:

Ở bài viết này mình demo 2 loại: List Object và Dataset.

FULL SOURCE CODE C#

using DevExpress.XtraPrinting.Preview;
using DevExpress.XtraPrintingLinks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Links;

using DevExpress.XtraReports.UI;

namespace PrintInvoice
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public List<Invoice> GetSampleData()
        {
            List<Invoice> invoices = new List<Invoice>
    {
        new Invoice
        {
            InvoiceNo = 1001,
            InvoiceDate = new DateTime(2023, 4, 15),
            CustomerName = "Nguyễn Thảo",
            TotalAmount = 1250.75m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product A", Quantity = 2, UnitPrice = 100.50m, TotalPrice = 201.00m },
                new InvoiceItem { ItemName = "Product B", Quantity = 5, UnitPrice = 75.25m, TotalPrice = 376.25m },
                new InvoiceItem { ItemName = "Product C", Quantity = 3, UnitPrice = 224.50m, TotalPrice = 673.50m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1002,
            InvoiceDate = new DateTime(2023, 4, 18),
            CustomerName = "Cái Trí Minh",
            TotalAmount = 875.40m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product D", Quantity = 1, UnitPrice = 375.60m, TotalPrice = 375.60m },
                new InvoiceItem { ItemName = "Product E", Quantity = 4, UnitPrice = 124.95m, TotalPrice = 499.80m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1003,
            InvoiceDate = new DateTime(2023, 4, 20),
            CustomerName = "Võ Sơn Băng",
            TotalAmount = 1500.00m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product F", Quantity = 3, UnitPrice = 200.00m, TotalPrice = 600.00m },
                new InvoiceItem { ItemName = "Product G", Quantity = 2, UnitPrice = 150.75m, TotalPrice = 301.50m },
                new InvoiceItem { ItemName = "Product H", Quantity = 1, UnitPrice = 500.25m, TotalPrice = 500.25m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1004,
            InvoiceDate = new DateTime(2023, 4, 22),
            CustomerName = "Nguyễn Đình Tuyên",
            TotalAmount = 990.50m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product I", Quantity = 2, UnitPrice = 110.25m, TotalPrice = 220.50m },
                new InvoiceItem { ItemName = "Product J", Quantity = 3, UnitPrice = 75.00m, TotalPrice = 225.00m },
                new InvoiceItem { ItemName = "Product K", Quantity = 4, UnitPrice = 140.00m, TotalPrice = 560.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1005,
            InvoiceDate = new DateTime(2023, 4, 25),
            CustomerName = "Hoàng Thị Thảo",
            TotalAmount = 675.80m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product L", Quantity = 1, UnitPrice = 375.80m, TotalPrice = 375.80m },
                new InvoiceItem { ItemName = "Product M", Quantity = 2, UnitPrice = 150.00m, TotalPrice = 300.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1006,
            InvoiceDate = new DateTime(2023, 4, 28),
            CustomerName = "Nguyễn Phương Nhi",
            TotalAmount = 1150.25m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product N", Quantity = 3, UnitPrice = 200.25m, TotalPrice = 600.75m },
                new InvoiceItem { ItemName = "Product O", Quantity = 2, UnitPrice = 175.50m, TotalPrice = 351.00m },
                new InvoiceItem { ItemName = "Product P", Quantity = 1, UnitPrice = 275.00m, TotalPrice = 275.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1007,
            InvoiceDate = new DateTime(2023, 5, 1),
            CustomerName = "Trịnh Quốc Khang",
            TotalAmount = 1450.60m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product Q", Quantity = 4, UnitPrice = 150.50m, TotalPrice = 602.00m },
                new InvoiceItem { ItemName = "Product R", Quantity = 2, UnitPrice = 175.75m, TotalPrice = 351.50m },
                new InvoiceItem { ItemName = "Product S", Quantity = 1, UnitPrice = 500.10m, TotalPrice = 500.10m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1008,
            InvoiceDate = new DateTime(2023, 5, 4),
            CustomerName = "Đinh Minh Thành",
            TotalAmount = 970.25m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product T", Quantity = 1, UnitPrice = 450.25m, TotalPrice = 450.25m },
                new InvoiceItem { ItemName = "Product U", Quantity = 3, UnitPrice = 140.00m, TotalPrice = 420.00m },
                new InvoiceItem { ItemName = "Product V", Quantity = 2, UnitPrice = 100.00m, TotalPrice = 200.00m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1009,
            InvoiceDate = new DateTime(2023, 5, 7),
            CustomerName = "Nguyễn Đình Tuyên",
            TotalAmount = 825.90m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product W", Quantity = 2, UnitPrice = 200.25m, TotalPrice = 400.50m },
                new InvoiceItem { ItemName = "Product X", Quantity = 1, UnitPrice = 425.50m, TotalPrice = 425.50m }
            }
        },
        new Invoice
        {
            InvoiceNo = 1010,
            InvoiceDate = new DateTime(2023, 5, 10),
            CustomerName = "Hoàng Dược Sư",
            TotalAmount = 550.40m,
            InvoiceItems = new List<InvoiceItem>
            {
                new InvoiceItem { ItemName = "Product Y", Quantity = 3, UnitPrice = 100.00m, TotalPrice = 300.00m },
                new InvoiceItem { ItemName = "Product Z", Quantity = 2, UnitPrice = 75.20m, TotalPrice = 150.40m }
            }
        }
    };

            return invoices;
        }


        public DataSet GetSampleDataSet()
        {
            DataSet dataSet = new DataSet();

            DataTable masterTable = new DataTable("Invoice");
            masterTable.Columns.Add("InvoiceNo", typeof(int));
            masterTable.Columns.Add("InvoiceDate", typeof(DateTime));
            masterTable.Columns.Add("CustomerName", typeof(string));
            masterTable.Columns.Add("TotalAmount", typeof(decimal));
            dataSet.Tables.Add(masterTable);

            DataTable detailTable = new DataTable("InvoiceItem");
            detailTable.Columns.Add("InvoiceNo", typeof(int));
            detailTable.Columns.Add("ItemName", typeof(string));
            detailTable.Columns.Add("Quantity", typeof(int));
            detailTable.Columns.Add("UnitPrice", typeof(decimal));
            detailTable.Columns.Add("TotalPrice", typeof(decimal));
            dataSet.Tables.Add(detailTable);

            dataSet.Relations.Add("Invoice_InvoiceItem", masterTable.Columns["InvoiceNo"], detailTable.Columns["InvoiceNo"]);

            List<Invoice> invoices = GetSampleData();
            foreach (Invoice invoice in invoices)
            {
                DataRow masterRow = masterTable.NewRow();
                masterRow["InvoiceNo"] = invoice.InvoiceNo;
                masterRow["InvoiceDate"] = invoice.InvoiceDate;
                masterRow["CustomerName"] = invoice.CustomerName;
                masterRow["TotalAmount"] = invoice.TotalAmount;
                masterTable.Rows.Add(masterRow);

                foreach (InvoiceItem item in invoice.InvoiceItems)
                {
                    DataRow detailRow = detailTable.NewRow();
                    detailRow["InvoiceNo"] = invoice.InvoiceNo;
                    detailRow["ItemName"] = item.ItemName;
                    detailRow["Quantity"] = item.Quantity;
                    detailRow["UnitPrice"] = item.UnitPrice;
                    detailRow["TotalPrice"] = item.TotalPrice;
                    detailTable.Rows.Add(detailRow);
                }
            }

            return dataSet;
        }


        private void simpleButton1_Click(object sender, EventArgs e)
        {

            var invoices = GetSampleData();

            var report = new rptInvoice();

            report.DataSource = invoices;

            var printTool = new DevExpress.XtraReports.UI.ReportPrintTool(report);

            printTool.ShowPreviewDialog();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {

            var invoices = GetSampleDataSet();

            var report = new rptInvoiceDataSet();

            report.DataSource = invoices;

            var printTool = new DevExpress.XtraReports.UI.ReportPrintTool(report);

            printTool.ShowPreviewDialog();
        }
    }



    public class Invoice
    {
        public int InvoiceNo { get; set; }
        public DateTime InvoiceDate { get; set; }
        public string CustomerName { get; set; }
        public decimal TotalAmount { get; set; }
        public List<InvoiceItem> InvoiceItems { get; set; }
    }

    public class InvoiceItem
    {
        public string ItemName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalPrice { get; set; }
    }
}


DOWNLOAD FULL SOURCE CODE.

DOWNLOAD SOURCE CODE


on Thứ Ba, 23 tháng 4, 2024 | , , , | A comment?