[C#] Login Form Sliding Animtion Effect Winform

Xin chào các bạn, bài viết này mình hướng dẫn các bạn cách tích hợp login form html và css vào Winform C#, và cách gọi thông tin giữa web với C# qua JS bằng ExcuteJavascript qua trình duyệt Webview2.

[C#] Login Form Sliding Animtion Effect Winform

[C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect

Video demo ứng dụng:

Để thực hiện bài viết, các bạn cần tìm hiểu về control webview2 trên website.

Webview2 có thể chạy tốt: CSS3, ReactJS, VueJS, AngularJs...

Ở bên tập lệnh javascript chúng ta viết lệnh như sau:
document.addEventListener('click', function (event)
{
    let elem = event.target;
    let jsonObject =
    {
        Key: 'click',
        Value: elem.id    //elem.name || elem.id || elem.tagName || "Unkown"
    };
    window.chrome.webview.postMessage(jsonObject);
});

Các bạn thấy ở hàm này, nó sẽ lắng nghe sự kiện trên toàn bộ trang web, khi nó bắt được sự kiện click. Nó sẽ lấy thông tin ID, các bạn có thể thay thế bằng: Name, id, tagname... và dùng lệnh:

Window.chrome.webview.postMessage về. Thì ở C#, chúng ta sẽ bắt được ở sự kiện:
private async void WebView21_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
{
    var jsonObject = JsonConvert.DeserializeObject<JsonObject>(e.WebMessageAsJson);
    var idElemnt = jsonObject.Value;
    switch (jsonObject.Key)
    {
        case "click":
            if(idElemnt != null && idElemnt != "")
            {
                if(idElemnt == "btnLogin")
                {
                   await ProcessLogin();
                }
            }
            break;

    }
}

Ở C#, chúng ta sẽ biết được nó vừa click ở id hoặc element nào.

Chi tiết các bạn có thể download source code bên dưới về để tham khảo.

Full source code C# form login.cs:

using Newtonsoft.Json;
using System;
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.Windows.Forms;

namespace AnimationSliding_Sign_In_Sign_Up
{
    public partial class FrmLogin : Form
    {
        private Microsoft.Web.WebView2.WinForms.WebView2 webView21;
        public FrmLogin()
        {
            InitializeComponent();
            webView21 = new Microsoft.Web.WebView2.WinForms.WebView2();
            webView21.EnsureCoreWebView2Async();
            InitLoadHtml();

        }

        private void InitLoadHtml()
        {          

            webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted;
            webView21.Dock = DockStyle.Fill;
            this.Controls.Add(webView21);
        }

        private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            string curDir = Directory.GetCurrentDirectory();
            var uri = new Uri(String.Format("file:///{0}/html/index.html", curDir));
            webView21.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
          
            webView21.CoreWebView2.Navigate(uri.ToString());
            webView21.WebMessageReceived += WebView21_WebMessageReceived;
        }
        public struct JsonObject
        {
            public string Key;
            public string Value;
        }

        private  async Task<string> GetTextboxValue(string elementId)
        {
            string script = $"document.getElementById('{elementId}').value";
            var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
            return result.Trim('"');
        }

        private async Task SetFocus(string elementId)
        {
            string script = $"setFocusOnInput('{elementId}');";
            var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
           
        }

        private async Task ShowSnackBar(string message, int timeout = 3000)
        {
            message = $"<i class="fa fa-exclamation-triangle" style="color: white; font-size: 16px;"> </i> {message}";
            string script = $"showSnackbar('{message}', {timeout});";
            var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
          
        }

        private async void WebView21_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
        {
            var jsonObject = JsonConvert.DeserializeObject<JsonObject>(e.WebMessageAsJson);
            var idElemnt = jsonObject.Value;
            switch (jsonObject.Key)
            {
                case "click":
                    if(idElemnt != null && idElemnt != "")
                    {
                        if(idElemnt == "btnLogin")
                        {
                           await ProcessLogin();
                        }
                    }
                    break;

            }
        }

        private async Task ProcessLogin()
        {
            var username = await GetTextboxValue("txtUsername");
            var password = await GetTextboxValue("txtPassword");
            if(username == "")
            {
                await ShowSnackBar("Chưa nhập tên đăng nhập, bạn ơi.");
                await SetFocus("txtUsername");
                return;
            }

            if (password == "")
            {
                await ShowSnackBar("Chưa nhập mật khẩu, bạn ơi.");
                await SetFocus("txtPassword");
                return;
            }

            if( password == "admin")
            {
                var frm = new FrmMain(username);
                frm.Show();
                this.Hide();
            }
            else
            {
                await ShowSnackBar("Tên đăng nhập hoặc mật khẩu không đúng, bạn ơi.");
            }

        }
    }
}

Chúc các bạn với thủ thuật tuyệt với này.

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

PASSWORD UNZIP: HUNG.PRO.VN
Chúc Mọi Người Thành Công Với Thủ Thuật Trên.
Nếu mọi người có vướng mắc gì mình chia sẽ trên trang có thể gửi liên hê cho mình tại đây nhé.
Cảm ơn mọi người đã quan tâm.

4 comments:

Hạ Tỷ Tỷ said...

thấy demo cũng ok nhưng đây là giao diện web chứ có phải app trên máy tính đâu a?

Hung Program VN said...

hehe, xem xét áp dụng vào web hay app e nhé <3

Learning Code said...

Chất lượng đó e (y)

Key HMA 2023 said...

nhìn cũng hay đấy? a xem xét để tích hợp vào chương trình của a. Để nhìn có vẽ ngầu hơn :D

All Right Reserved © 2015 By Hung Pro VN