Wednesday, July 16, 2008

Cách tạo shortcut trên Desktop cho ứng dụng được triển khai bằng ClickOnce

Khi thực hiện triển khai ứng dụng bằng ClickOnce, nó chỉ tạo ra shortcut trên All Programs menu với đường dẫn là <CompanyName>/<ProductName>, trong đó <CompanyName> và <ProductName> đã được đăng ký trong Assembly của ứng dụng. Đoạn code sau đây sẽ thực hiện việc tự động copy shortcut từ trên menu Programs vào Desktop. Bạn nên đưa phương thức này vào Form Main của ứng dụng.

//    Khi đưa vào chương trình nên chú ý kiểm tra xem bạn có đang debug trên Visual Studio hay không?
//    #if (!debug)
//        CheckForShortcut();
//    #endif
 
//Namespace Referrence
// using System.Deployment.Application;
// using System.Reflection;
 
void CheckForShortcut()
{
    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
 
    if (ad.IsFirstRun)
    {
        Assembly code = Assembly.GetExecutingAssembly();
 
        string company = string.Empty;
        string productName = string.Empty;
 
        if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
        {
            AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(
                code, typeof(AssemblyCompanyAttribute));
 
            company = ascompany.Company;
        }
 
        if (Attribute.IsDefined(code, typeof(AssemblyProductAttribute)))
        {
 
            AssemblyProductAttribute asProductName = (AssemblyProductAttribute)Attribute.GetCustomAttribute(
                code, typeof(AssemblyProductAttribute));
 
            productName = asProductName.Product;
        }
 
        if (company != string.Empty && productName != string.Empty)
        {
 
            string desktopPath = string.Empty;
 
            desktopPath = string.Concat(Environment.GetFolderPath(
                Environment.SpecialFolder.Desktop), "\\", productName, ".appref-ms");
 
            string shortcutName = string.Empty;
 
            shortcutName = string.Concat(
                Environment.GetFolderPath(Environment.SpecialFolder.Programs),
                "\\", company, "\\", productName, ".appref-ms");
 
            System.IO.File.Copy(shortcutName, desktopPath, true);
        }
    }
}

No comments:

Post a Comment