Hiển thị các bài đăng có nhãn CSHARP. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn CSHARP. 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?

[CSHARP] Instructions for push notifications using One Signal API

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 push notification cho website sử dụng API One Signal C#.

[CSHARP] Hướng Dẫn Push Notification Sữ Dụng API One Signal

One Signal giúp chúng ta dễ dàng gởi thông báo đến tất cả các webclient đã đăng ký nhận thông báo từ ứng dụng web của chúng ta.

Sử dụng One Sign sẽ giúp tăng SEO cho website của chúng ta, mỗi khi có bài viết mới thì người dùng dễ dàng nhận được thông báo một cách nhanh chóng.

Dưới đây là giao diện demo ứng dụng:


Trong ứng dụng trên, mình chỉ push các thông tin cơ bản, bao gồm:
 
Tiêu đề, nội dung, link khi mở vào, và hình ảnh bài viết (chỉ tích hợp chạy trên chrome).
Khi các bạn nhấn nút Push vào thì ứng dụng sẽ gởi thông báo đến tất cả các client đã đăng ký như hình bên dưới.

Đầu tiên, các bạn cần import thư viện vào từ Nuget:
PM> Install-Package OneSignal.CSharp.SDK

Các bạn cần lấy ID app, API Sercet key từ setting của onesignal để thêm vào ứng dụng nhé.

Và dưới đây là source code khi click vào button Push Notification:
using OneSignal.CSharp.SDK;
using OneSignal.CSharp.SDK.Resources;
using OneSignal.CSharp.SDK.Resources.Notifications;
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 Push_Notification_OneSignal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_push_Click(object sender, EventArgs e)
        {
            var client = new OneSignalClient("Nhập Serect key của bạn"); // Nhập API Serect Key

            var options = new NotificationCreateOptions_new();

            options.AppId = new Guid("Nhập ID SignOne"); // Nhập My AppID của bạn
            options.IncludedSegments = new List<string> { "All" };
            options.Headings.Add(LanguageCodes.English, txt_title.Text);
            options.Contents.Add(LanguageCodes.English, txt_content.Text);
            options.Url = txt_link.Text;
            options.ChromeWebImage = txt_url_image.Text;
            var result =  client.Notifications.Create(options);
            MessageBox.Show(result.ToString());
        }
    }
}

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

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN 

on Thứ Sáu, 5 tháng 7, 2024 | , , , , | A comment?

[CSHARP] Instructions for automatically generating OTP codes in Csharp programming

[CSHARP] Instructions for automatically generating OTP codes in Csharp programming
Chào các bạn trẻ thân mến, bài viết hôm nay mình sẽ hướng dẫn các bạn cách tạo mã OTP tự động trong lập trình C# (tạo password tự động).

[CSHARP] Hướng dẫn tạo mã tự động OTP trong lập trình Csharp

Vậy OTP là gì?

OTP là viết tắt của từ One Time Password, có nghĩa là mật khẩu sử dụng 1 lần.
Mã OTP là mã được các hệ thống thanh toán online mặc định gửi đến cho quý khách hàng để nhập vào trong thời gian thực hiện giao dịch để đảm bảo sự bảo mật một cách tối đa.

Nếu bạn nào thường sử dụng Internet Banking thì thường gặp mã OTP, khi giao dịch một dịch vụ nào, thì ngân hàng hàng sẽ gởi cho chúng ta một mã OTP và có thời gian sử dụng trong thời gian nhất định.

Trong ngôn lập lập trình .NET có hỗ trợ cho chúng ta tất cả là 3 hàm Random:
  1. Next() => hàm Next trả về cho chúng ta ngẫu nhiên một số
  2. NextBytes() => hàm trả về random cho chúng ta một mảng byte.
  3. NextDouble() => hàm random trả về cho chúng ta từ 0.0 - 1.0.
Để tạo random OTP, bao gồm các ký tự chữ hoa, chữ thường, số, và các ký tự đặc biệt.

Trong bài viết này, mình sẽ sử dụng hàm NextDouble() để thực hiện.

Dưới đây, mình sẽ viết hàm makeRandomPassword trả về cho chúng ta một dãy số ngẫu nhiên, và số ký tự trả về chúng ta sẽ truyền qua parametter.

Source code OTP C# viết bằng Console Application C#

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
namespace PasswordPractice {  
    class PasswordCreate {  
        //Tis function is making the Random Password  
        public string makeRandomPassword(int length) {  
            string UpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM";  
            string LowerCase = "qwertyuiopasdfghjklzxcvbnm";  
            string Digits = "1234567890";  
            string allCharacters = UpperCase + LowerCase + Digits;  
            //Random will give random charactors for given length  
            Random r = new Random();  
            String password = "";  
            for (int i = 0; i < length; i++) {  
                double rand = r.NextDouble();  
                if (i == 0) {  
                    password += UpperCase.ToCharArray()[(int) Math.Floor(rand * UpperCase.Length)];  
                } else {  
                    password += allCharacters.ToCharArray()[(int) Math.Floor(rand * allCharacters.Length)];  
                }  
            }  
            Console.WriteLine(password);  
            Console.ReadLine();  
            return password;  
        }  
        static void Main(string[] args) {  
            //User Input  
            Console.WriteLine("Enter length of password");  
            string len = Console.ReadLine();  
            PasswordCreate n = new PasswordCreate();  
            //Call the method in main method  
            n.makeRandomPassword(Convert.ToInt32(len));  
        }  
    }  
}  

Hình ảnh sau khi chạy chương trình.

Chúc các bạn thành công với tiện ích này.

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

[CSHARP] Drag drop file to RichTextBox

[CSHARP] Drag drop file to RichTextBox
Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách Drag drop file Text vào RichTextBox trên C# winform.

[C#] Hướng dẫn Drag and Drop File vào RichTextBox

Dưới đây là hình ảnh demo mình kéo file text vào RichTextBox.

Source code C#:

namespace Drag_Drop_RichTextBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

 

        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.AllowDrop = true;
            richTextBox1.DragDrop += RichTextBox1_DragDrop;
        }

        private void RichTextBox1_DragDrop(object sender, DragEventArgs e)
        {
            var data = e.Data.GetData(DataFormats.FileDrop);
            if (data != null)
            {
                var fileNames = data as string[];
                if (fileNames.Length > 0) {
                    string myText = File.ReadAllText(fileNames[0], Encoding.UTF8);
                    richTextBox1.Text = myText;
                }
                
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://laptrinhvb.net");
        }
    }
}

Các bạn chỉ cần Enable thuộc tính AllowDrop = true.

và viết sự kiện drapdrop trên richtextbox như source code ở trên.
Chúc các bạn thành công với thủ thuật trên.

[CSHARP] Instructions for checking whether Gmail exists or not in csharp programming

Bài viết hôm nay, mình sẽ hướng dẫn các bạn cách kiểm tra một email có tồn tại hay không trong lập trình C#?
 
Bài viết hướng dẫn dưới đây mình sử dụng thư viện: EmailValidator.NET

[CSHARP] Hướng dẫn kiểm tra Gmail có tồn tại hay không trong lập trình csharp

Thư viện EmailValidator.NET chỉ hỗ trợ kiểm tra email trên hệ thống google mail (Gmail) thôi các bạn nhé.

Nếu các bạn nào có cách validator được hết các email thì có thể để lại comment bên dưới, góp ý thêm cho mình.

- Cài đặt thư viện EmailValidator.NET.

Cài đặt từ Nuget với câu lệnh sau:
Install-Package EmailValidator.NET

Hướng dẫn sử dụng thư viện code C#:
EmailValidator emailValidator = new EmailValidator();
EmailValidationResult result;

if (!emailValidator.Validate(email, out result))
{
    Console.WriteLine("Unable to check email") // no internet connection or mailserver is down / busy
}

switch (result)
{
    case EmailValidationResult.OK:
        Console.WriteLine("Mailbox exists");
        break;

    case EmailValidationResult.MailboxUnavailable:
        Console.WriteLine("Email server replied there is no such mailbox");
        break;

    case EmailValidationResult.MailboxStorageExceeded:
        Console.WriteLine("Mailbox overflow");
        break;

    case EmailValidationResult.NoMailForDomain:
        Console.WriteLine("Emails are not configured for domain (no MX records)");
        break;
}

Chúc mọi người thành công với thủ thuật trên, để tạo cho bản thân một chương trình tốt.
Theo LapTrinhVB.Net

on Thứ Ba, 2 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] Switch the running application to Admin mode

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 chuyển đổi ứng dụng sang chạy chế độ Run As Administrator trong lập trình C#.

[CSHARP] Chuyển ứng dụng chạy sang chế độ Admin

Trên ứng dụng của bạn, nếu bạn muốn chuyển ứng dụng mình sang chế độ Admin khi click vào button thì sẽ mở form mới và chạy chế độ Admin.

[CSHARP] Chuyển ứng dụng chạy sang chế độ Admin

Từ phiên bản win 7 trở lên, thường thì ứng dụng của bạn không được phép ghi vào ổ đĩa C: của hệ thống.

Nếu ứng dụng, của bạn muốn ghi file được thì cần phải chạy ở chế độ Run AS Administrator.

Code C# Run App as Administrator

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length > 1 && args[1] == "-e") Text = "Elevated";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Process process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = Application.ExecutablePath,
                Arguments = "-e",
                Verb = "runas",//-Admin.
            }
        };
        process.Start();
    }
}

Qua đoạn code trên các bạn đã cho chương trình mình chỉ hoạt động trên quyền admin thì chương trình mới hoạt động, còn nếu bạn không chạy dưới quyền admin thì nó sẽ không hoạt động nhé.

Chúc mọi người thành công với đoạn code trên.

[CSHARP] How to Save and Get Password in Credential Manager Windows

[CSHARP] Hướng dẫn lưu trữ mật khẩu ở Credential Manage Windows

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách lưu trữ mật khẩu ứng dụng vào Credential Manager trên Windows.

[CSHARP] Hướng dẫn lưu trữ mật khẩu ở Credential Manage Windows

Trên Microsoft Windows, có một ứng dụng Credential Manager dùng để lưu trữ thông tin username và password của một ứng dụng hoặc Website.
Để truy cập vào Credential Manager:
Các bạn vào ControlPanel > All Control Panel Items > Credential manger như hình bên dưới.
Bài viết này mình sẽ hướng dẫn các bạn cách lưu trữ mật khẩu ứng dụng vào đây, như hình bên dưới:
Ở hình trên, các bạn thấy mình đã lưu trữ ứng dụng: laptrinhvbApp Để thực hiện, các bạn cần cài đặt thư viện Credentials từ Nuget:
PM> NuGet\Install-Package Credentials -Version 2.0.0.30

Bước 1: Tạo một class PasswordRepository chứa hai phương thức: SavePassword và GetPassword

public class PasswordRepository
{      

    public void SavePassword(string AppName, string password)
    {
        using (var cred = new Credential())
        {
            cred.Password = password;
            cred.Target = AppName;
            cred.Type = CredentialType.Generic;
            cred.PersistanceType = PersistanceType.LocalComputer;
            cred.Save();
        }
    }

    public string GetPassword(string AppName)
    {
        using (var cred = new Credential())
        {
            cred.Target = AppName;
            cred.Load();
            return cred.Password;
        }
    }
}

Bước 2: Sử dụng hàm trên để lưu trữ mật khẩu

private void button1_Click(object sender, EventArgs e)
{
    var AppName = "laptrinhvbApp";
    new PasswordRepository().SavePassword(AppName, "Laptrinhvb.net");
    var data = new PasswordRepository().GetPassword(AppName);
}
Chúc các bạn thành công với thủ thuật lưu mật khẩu trên, và không lo việc quên mật khẩu nữa.

on Thứ Sáu, 28 tháng 6, 2024 | , , | A comment?

[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

[CSHAR] How to Lock and Unlock User in Domain Windows.

[CSHAR] How to Lock and Unlock User in Domain Windows.

Xin chào các bạn, bài viết hôm nay mình tiếp tục chia sẻ các bạn source code cách khóa và mở khóa (lock and unlock) tài khoản người dùng user trong domain Windows bằng C#.

[C#] Chia sẻ code lock và unlock user trong domain Window

Để khóa và mở khóa được tài khoản user trong domain.

Các bạn cần phải có tài khoản của Admin Domain, thì các bạn mới có thể khóa và mở khóa cho user được.

Ở bài này, mình chia sẻ function, các bạn có thể copy và sử dụng nó.

Source code C#:

Ở hàm dưới này, các bạn cần truyền vào 4 tham số để hoạt động:
  1. username: là tài khoản user cần thao tác khóa hoặc mở khóa
  2. domain: tên domain của bạn ex: hung.pro.vn
  3. Admin_User: nhập tài khoản User_domain
  4. Admin_Password: nhập mật khẩu Password_domain

Full Source Code

using System;
using System.DirectoryServices;

class Program
{
    static void Main()
    {
        string username = "User_LockorUnLock"; // Specify the username of the account you want to unlock or lock
        string domain = "hung.pro.vn"; // Specify your domain name
        string Admin_User = "User_domain"; // Specify the username of your administrator account
        string Admin_Password = "Password_domain"; // Specify the password of your administrator account

        UnlockOrLockUserAccount(username, domain, userAdmin, passAdmin);
    }

    static void UnlockOrLockUserAccount(string username, string domain, string userAdmin, string passAdmin)
    {
        try
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userAdmin, passAdmin);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(&(objectClass=user)(samAccountName=" + username + "))";
            SearchResult result = searcher.FindOne();

            if (result != null)
            {
                DirectoryEntry userEntry = result.GetDirectoryEntry();
                int userFlags = (int)userEntry.Properties["userAccountControl"].Value;
                bool isAccountLocked = (userFlags & 0x2) == 0x2; // Check if the "account is locked" bit is set

                // Toggle the lock status
                if (isAccountLocked)
                {
                    // Account is currently locked, unlock it
                    int newFlags = userFlags & ~0x2; // Clear the "account is locked" bit
                    userEntry.Properties["userAccountControl"].Value = newFlags;
                    userEntry.CommitChanges();
                    Console.WriteLine("Account unlocked successfully.");
                }
                else
                {
                    // Account is currently unlocked, lock it
                    int newFlags = userFlags | 0x2; // Set the "account is locked" bit
                    userEntry.Properties["userAccountControl"].Value = newFlags;
                    userEntry.CommitChanges();
                    Console.WriteLine("Account locked successfully.");
                }
            }
            else
            {
                Console.WriteLine("User not found.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

Chúc mọi người thành công với thủ thuật trên, và có thể áp dụng để mỡ khóa một chương trình dạng domain cho người dùng trên internet cũng ok nhé mọi người.

on Thứ Bảy, 25 tháng 5, 2024 | , | A comment?

[CSHARP] Virtual Desktop

Virtual Desktop

Chào mọi người, hôm nay mình lại tiếp tục chia sẽ hco mọi người một ứng dụng khá hay trên window, một dạng cửa sổ windows mới hoàn toàn và như một máy tính riêng mới trên máy tính của bạn.

[C#] Run Application in Virtual Desktop Winform

Khi các bạn chạy ứng dụng của mình sẻ chạy độc lập trên một màn hình Desktop khác.

Khi chạy ứng dụng ở giao diện này sẽ có một số ưu nhược điểm khác nhau của từng người code nhé.

Ưu điểm:

  1. Giúp ứng dụng tăng bảo mật, chống keylogger... 

Nhược điểm:

  1. Zalo sẻ không chụp được màn hình.
  2. oặc không sử dụng được phím PrintScreen, và nhiều chức năng khác

Source code c# virtual Desktop:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RunAppinVirtualDesktop
{
    internal static class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags, uint dwDesiredAccess, IntPtr lpsa);

        [DllImport("user32.dll")]
        private static extern bool SwitchDesktop(IntPtr hDesktop);

        [DllImport("user32.dll")]
        public static extern bool CloseDesktop(IntPtr handle);

        [DllImport("user32.dll")]
        public static extern bool SetThreadDesktop(IntPtr hDesktop);

        [DllImport("user32.dll")]
        public static extern IntPtr GetThreadDesktop(int dwThreadId);

        [DllImport("kernel32.dll")]
        public static extern int GetCurrentThreadId();

        enum DESKTOP_ACCESS : uint
        {
            DESKTOP_NONE = 0,
            DESKTOP_READOBJECTS = 0x0001,
            DESKTOP_CREATEWINDOW = 0x0002,
            DESKTOP_CREATEMENU = 0x0004,
            DESKTOP_HOOKCONTROL = 0x0008,
            DESKTOP_JOURNALRECORD = 0x0010,
            DESKTOP_JOURNALPLAYBACK = 0x0020,
            DESKTOP_ENUMERATE = 0x0040,
            DESKTOP_WRITEOBJECTS = 0x0080,
            DESKTOP_SWITCHDESKTOP = 0x0100,

            GENERIC_ALL = (DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU |
                            DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK |
                            DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP),
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            IntPtr hOldDesktop = GetThreadDesktop(GetCurrentThreadId());
            IntPtr hNewDesktop = CreateDesktop("RandomDesktopName", IntPtr.Zero, IntPtr.Zero, 0, (uint)DESKTOP_ACCESS.GENERIC_ALL, IntPtr.Zero);

            SwitchDesktop(hNewDesktop);        


            Task.Factory.StartNew(() =>
            {
                SetThreadDesktop(hNewDesktop);

                Application.Run(new Form1());
            }).Wait();

            SwitchDesktop(hOldDesktop);
            CloseDesktop(hNewDesktop);
           
        }
    }
}

Qua đoạn code trên mọi người có thể tùy biến phù hợp với khả năng và sở thích của bản thân để tạo cho mình một chương trình virtual desktop tốt nhất để chia sẽ cho mọi người nhé.
Chúc các bạn thành công.

Download Source Code Virtual Desktop

PASSWORD UNZIP: HUNG.PRO.VN 

on Thứ Hai, 13 tháng 5, 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?