Showing posts with label API. Show all posts

[API] Thay đổi độ phân giải màn hình.

thuvienwinform - [API] Thiết đặt độ phân giải màn hình.

Nhiều lúc bạn muốn thay đổi độ phân giải của màn hình (Thường nếu viết Game mà hình nền không phải ảnh Vector thì nên thay đổi phân giải màn hình để hiển thị sắc nét nhất - rất rất nhiều game dùng cách này).
Hôm nay mình sẽ hướng dẫn các bạn cách để thay đổi độ phân giải màn hình. Code này là mình sưu tầm được và biến tấu đi tí cho dễ dùng thôi :))
OK. Bắt đầu nhé.

Trong Project mình tạo file Resolution.cs có nội dung sau (Cái này chỉ nhằm mục đích "phục vụ" cho class chính thôi)

 
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE1
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string dmDeviceName;
    public short dmSpecVersion;
    public short dmDriverVersion;
    public short dmSize;
    public short dmDriverExtra;
    public int dmFields;

    public short dmOrientation;
    public short dmPaperSize;
    public short dmPaperLength;
    public short dmPaperWidth;

    public short dmScale;
    public short dmCopies;
    public short dmDefaultSource;
    public short dmPrintQuality;
    public short dmColor;
    public short dmDuplex;
    public short dmYWindowsFormsApplication1;
    public short dmTTOption;
    public short dmCollate;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string dmFormName;
    public short dmLogPixels;
    public short dmBitsPerPel;
    public int dmPelsWidth;
    public int dmPelsHeight;

    public int dmDisplayFlags;
    public int dmDisplayFrequency;

    public int dmICMMethod;
    public int dmICMIntent;
    public int dmMediaType;
    public int dmDitherType;
    public int dmReserved1;
    public int dmReserved2;

    public int dmPanningWidth;
    public int dmPanningHeight;
};



class User_32
{
    [DllImport("user32.dll")]
    public static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE1 devMode);
    [DllImport("user32.dll")]
    public static extern int ChangeDisplaySettings(ref DEVMODE1 devMode, int flags);

    public const int ENUM_CURRENT_SETTINGS = -1;
    public const int CDS_UPDATEREGISTRY = 0x01;
    public const int CDS_TEST = 0x02;
    public const int DISP_CHANGE_SUCCESSFUL = 0;
    public const int DISP_CHANGE_RESTART = 1;
    public const int DISP_CHANGE_FAILED = -1;
}

Tiếp theo là class chính : Ở đây mình đặt tên là SmartScreen (Nghe cho nguy hiểm)
 
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace SmartScreen
{
    public class Resolution
    {
        /// 
        /// Chuyển đổi độ phân giải màn hình
        /// Trả về chuỗi mô tả (Thành công hay thất bại)
        /// 
        /// Chiều rộng
        /// Chiều ngang
        /// 
        public static string SetResolution(int w, int h)
        {
            Screen screen = Screen.PrimaryScreen;

            int iWidth = w;
            int iHeight = h;


            DEVMODE1 dm = new DEVMODE1();
            dm.dmDeviceName = new String(new char[32]);
            dm.dmFormName = new String(new char[32]);
            dm.dmSize = (short)Marshal.SizeOf(dm);

            if (0 != User_32.EnumDisplaySettings(null, User_32.ENUM_CURRENT_SETTINGS, ref dm))
            {

                dm.dmPelsWidth = iWidth;
                dm.dmPelsHeight = iHeight;

                int iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_TEST);

                if (iRet == User_32.DISP_CHANGE_FAILED)
                {
                    return "Unable to process your request";
                }
                else
                {
                    iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_UPDATEREGISTRY);

                    switch (iRet)
                    {
                        case User_32.DISP_CHANGE_SUCCESSFUL:
                            {
                                return "Success";
                            }
                        case User_32.DISP_CHANGE_RESTART:
                            {

                                return "restart";
                            }
                        default:
                            {
                                return "Failed";
                            }
                    }
                }

            }

            return "Skip";
        }

        /// 
        /// Lấy phân giải màn hình
        /// Trả Point
        /// 
        /// 
        public static Point GetResolution()
        {
            Screen Srn = Screen.PrimaryScreen;
            Point res = new Point(Srn.Bounds.Width, Srn.Bounds.Height);
            
            return res;
        }
    }
}

OK giờ muốn thay đổi độ phân giải bạn chỉ cần gọi : SmartScreen.SetResolution(Chiều rộng, Chiều dài);
Hẹn gặp lại nhé ^^ Dạo này bận quá !
1/20/2015
Đăng bởi :
Nhãn :

[API] Ini - Ghi các setting cực tốt !

Với một phần mềm có chức năng tùy chỉnh thì việc lưu các setting là rất quan trọng.
Hôm nay mình xin hướng dẫn các bạn một trong các kiểu ghi/đọc các setting cực kì phổ biến -- Đọc/Ghi Ini

1. Tổng quan một file ini
1 file được ghi theo kiểu Ini sẽ có dạng sau đây :
[Section]
Key=Value

Ví dụ mình muốn lưu cái "Tự động đăng nhập" cho phần mềm của mình thì File ini sẽ có dạng sau :
[TuDongDangNhap]
KichHoat=1
TaiKhoan=buiducduy111

2. Thực hiện trong C#

2.1 . Đừng quên " using System.Runtime.InteropServices;" để có thể sử dụng các hàm API
2.2. Sử dụng DLL :  kernel32

[DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);

OK vậy là bạn có thể Đọc/Ghi dữ liệu từ file setting theo cách trên

Nếu chưa làm được hãy xem code dưới đây (Bạn chỉ cần sử dụng INI.READ và INI.WRITE thôi)
public class INI
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);

                      // Viết thêm 2 hàm mới cho dễ  
        public static string READ(string szFile, string szSection, string szKey)
        {
            StringBuilder tmp = new StringBuilder(255);
            long i = GetPrivateProfileString(szSection, szKey, "", tmp, 255, szFile);
            return tmp.ToString();
        }
        public static void WRITE(string szFile, string szSection, string szKey, string szData)
        {
            WritePrivateProfileString(szSection, szKey, szData, szFile);
        }
    }

3. Thực hành
Ví dụ : (Sử dụng class INI được xây dựng bên trên)
INI.WRITE("Data.ini","TuDongDangNhap","TaiKhoan", "buiducduy");
INI.WRITE("Data.ini","TuDongDangNhap","KichHoat", "1");
Kết quả trong Data.ini :
[TuDongDangNhap]
TaiKhoan=buiducduy111
KichHoat=1

string s = INI.READ("Data.ini","TuDongDangNhap","TaiKhoan");
MessageBox.Show(s);
Kết quả "buiducduy";

OK. Nếu chưa hiểu bạn cứ comment ở dưới nhé!

4/14/2014
Đăng bởi :
Nhãn : ,

[API] Phát nhạc MP3

Như chúng ta đã biết thư viện "System.Media" chỉ cho phép chạy file âm thanh ".wav" nhiều chúng ta chạy file MP3 rất khó khăn (làm một chương trình phát nhac đơn giản chẳng hạn -- không dùng dll của Windows Media đâu nhé)

Hôm nay mình sẽ hướng dẫn các bạn sử dụng API để chạy file MP3 trong C#.
Các bước như sau :

1. Đừng quên "using System.Runtime.InteropServices;" để sử dụng API nhé.

2. Import Dll "winmm.dll"
[DllImport("winmm.dll")]

private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

Hàm API này không hẳn có chức năng chạy MP3 mà nó là 1 hàm cho phép thực hiện câu lệnh được Coder đưa vào qua 1 string là strCommad . như vậy parameters này là quan trọng nhất (và mình cũng không biết các param khác có chức năng gì -- thôi thì cứ null -- API thường vậy mà HIHI ^^)

3. Giới thiệu các Commad để chạy 1 file MP3
- Mở MP3 :  "open "Đường dẫn tới file mp3" type mpegvideo alias MediaFile"
ví dụ : "open "E:\MUSIC\nhac.mp3" type mpegvideo alias MediaFile"
- Chạy MP3 vừa mở :  "play MediaFile"
Có thể dùng "play MediaFile REPEAT" để phát đi phát lại file MP3 vừa mở
- Dừng MP3 : "close MediaFile"


Nếu chưa làm được hãy xem ví dụ này :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MP3
{
    public partial class Form1 : Form
    {
        public bool isOpen = false;

        public Form1()
        {
            InitializeComponent();
        }
                  // Import Dll này vô
        [DllImport("winmm.dll")]'

        private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

        // BUTTON PLAY MP3
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Filter = "MP3 (*.mp3)|*.mp3";
            if (op.ShowDialog() == DialogResult.OK)
            {
                string szFile = op.FileName;
                MP3Open(szFile); 
                Mp3Play(false);
            }
        }
        // BUTTON STOP MP3
        private void button2_Click(object sender, EventArgs e)
        {
            Mp3Close();
        }

        // PHẦN XỬ LÍ ----------------------------------------------------------------------------------
        public void MP3Open(string szFileName)
        {
            string szCommad = "open \"" + szFileName + "\" type mpegvideo alias MediaFile";
            MessageBox.Show(szCommad);
           mciSendString(szCommand, null, 0, IntPtr.Zero);
            isOpen = true;
        }
        public void Mp3Close()
        {
            string szCommand = "close MediaFile";
            mciSendString(szCommand, null, 0, IntPtr.Zero);
            isOpen = false;
        }

        public void Mp3Play(bool isLoop)
        {
            if (isOpen)
            {
                string szCommand = "play MediaFile";
                if (isLoop) szCommand += " REPEAT";
                mciSendString(szCommand, null, 0, IntPtr.Zero);
            }
        }
    }
}

4/13/2014
Đăng bởi :
Nhãn : ,

[API] Kiểm tra kết nối Internet

Trong nhiều chương trình, chúng ta cần thao tác với Server qua Network , song nếu máy tính chưa kết nối Internet thì chương trình rất có thể bị "Treo" do cố gắng làm những công việc bạn code (Đơn giản như chương trình gửi mail - hãy thử ngắt kết nối Internet và chạy chương trình :D)

Hôm nay mình sẽ hướng dẫn các bạn làm sao để kiểm tra máy tính có đang kết nối Internet !

1. Nhớ "using System.Runtime.InteropServices;"  để có thể sử dụng API

2. Import DLL "wininet.dll"
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

Ở đây hàm này sẽ trả về true nếu có kết nối internet và false nếu không ^^!


* Nếu các bạn chưa làm được có thể xem ví dụ dưới đây

    public class INTERNET
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int                                                                                                                                        ReservedValue);
        public static bool ISINTERNETCONNECTED()
        {
            int des;
            if (InternetGetConnectedState(out des, 0) == true)
                return true;
            return false;        }
   }





Đăng bởi :
Nhãn : ,

API là gì? Ứng dụng của nó như thế nào?


thuvienwinform - Đơn giản như thế này, hiện nay nhiều người dùng mạng xã hội facebook và bạn muốn viết một ứng dụng để đăng tin lên mạng xã hội này. Vậy làm sao để làm một ứng dụng như vậy khi facebook là của người khác? Hiểu được nhu cầu này của các lập trình viên facebook sẽ đưa ra các thư viện chứa các hàm đăng, like, share...trên trang của mình để các lập trình viên khai thác! Đó chính là API
Google+, Gmail, Blogger, Youtube, các ứng dụng của windows (Windows media player, Internet Explorer,..), nhaccuatui, zingmp3,...rất nhiều các trang web, ứng dụng đưa ra các API để hỗ trợ các lập trình viên

- API (Application Programming Interface - Giao diện lập trình ứng dụng). Mỗi hệ điều hành, ứng dụng đều có những bộ API khác nhau. Nó cung cấp cho người lập trình các hàm tương tác với CSDL, lập trình thực hiện các thao tác với hđh hay phần mềm đó. Hầu hết các hàm API được chứa trong các file DLL
- Ví dụ: Các hàm API của hđh windows cho phép chúng ta lập trình ứng dụng thay đổi icon màn hình, xem thông tin máy tính, ... hay các hàm API của google cho phép lập trình viên lấy thông tin, sửa thông tin người dùng,...Các hàm API của facebook cho chúng ta đăng stt, ảnh, cmt,...
- Vậy API có phải một ngôn ngữ lập trình không? Câu trả lời là không các bạn ạ. Các hàm API cũng như các hàm bình thường mà chúng ta hay viết và trên từng ngôn ngữ khác nhau cũng có các bộ API tương ứng khác nhau.
- Ví dụ: Google API có bộ cho .NET, PHP,..
- Và mỗi bộ API hầu như đều có hướng dẫn sử dụng rất cụ thể và chi tiết. Ví dụ của hướng dẫn sử dụng các hàm API đối với blogger: https://developers.google.com/blogger/docs/2.0/developers_guide_dotnet rất hữu ích cho ai muốn viết ứng dụng quản lí blog


- Ví dụ một đoạn code đăng bài cho blog sử dụng API của google:

void DangBai(Service service, string bID, string title, string content, bool isDraft)
        {
            //Tạo các thuộc tính của bài đăng
            Uri blogPostUri = new Uri("http://www.blogger.com/feeds/" + bID + "/posts/default");
            AtomEntry newPost = null;
            newPost = new AtomEntry();
            newPost.IsDraft = isDraft;
            newPost.Title.Text = title;

            newPost.Content = new AtomContent();
            newPost.Content.Content = content;
            newPost.Content.Type = "html";
            newPost.Updated = new DateTime(2011, 1, 1, 10, 0, 0);
            newPost.Published = new DateTime(2011, 1, 1, 10, 0, 0);
            //Đăng bài
            AtomEntry CreateEntry = service.Insert(blogPostUri, newPost);
        }

Một số bài về API:
- Phát nhạc: http://thuvienwinform.blogspot.com/2014/04/api-phat-nhac-mp3_13.html
- Kiểm tra kết nối mạng: http://thuvienwinform.blogspot.com/2014/04/api-kiem-tra-ket-noi-internet.html
- Facebook API: http://facebooksdk.net/
- Google API: https://code.google.com/p/google-api-dotnet-client/wiki/APIs
+ Hướng dẫn A-Z Google API cho Blogspot: http://garyngzhongbo.blogspot.com/2013/10/bloggerc-blogger-api-v31.html
- Tìm trên nhaccuatui: http://diendan.congdongcviet.com/threads/t57486::lay-link-nhac-an-tu-trang-nhaccuatui-com.cpp

11/27/2013
Đăng bởi :
Nhãn : ,

Nhận ngay 100$ cho VPS

Mua hàng ủng hộ page

Ủng hộ page

Nhãn

Code (45) Team Foundation Server (17) Database (14) News (14) product (13) toolbox (10) Linq (9) SoftDesign (8) XNA (6) API (5) Project (5) item (4)

- Bản quyền thuộc về Thư Viện WinForm - Giao diện: Metrominimalist - Thiết kế: Johanes Djogan -