WindowsFormアプリの調査2

BackgroundWorkerの例外対応

okwakatta.net

インストーラ

Microsoft Visual Studio 2015 Installer Projects を利用してインストーラーを作成する .NET Visual Studio Installerを使ったインストーラの作成 - コンピューター100%

ErrorProvider

codezine.jp

ESCでFormを閉じる

nanoappli.com

画面の更新について

Update Refresh Invalidate の画面更新について (Windows7) - C#プログラミング

状態参考

www.backlog.jp www.backlog.jp

log解析ツール

log2console.codeplex.com

ランチャー

forest.watch.impress.co.jp

自動補完対応テキストボックス
// 使用方法
string[] _values = { "日本1", "日本1", "日本3", "東京", "埼玉", "神奈川", "千葉" };
this.autoCompleteTextBox1.Values = _values;
 public class AutoCompleteTextBox : TextBox
 {
     private ListBox _listBox;
     private bool _isAdded;
     private String[] _values;
     private String _formerValue = String.Empty;

     public AutoCompleteTextBox()
     {
         InitializeComponent();
         ResetListBox();
     }

     private void InitializeComponent()
     {
         _listBox = new ListBox();
         this.KeyDown += this_KeyDown;
         this.KeyUp += this_KeyUp;
     }

     private void ShowListBox()
     {
         if (!_isAdded)
         {
             Form parentForm = this.FindForm(); // new line added
             parentForm.Controls.Add(_listBox); // adds it to the form
             Point positionOnForm = parentForm.PointToClient(this.Parent.PointToScreen(this.Location)); // absolute position in the form
             _listBox.Left = positionOnForm.X;
             _listBox.Top = positionOnForm.Y + Height;
             _isAdded = true;
         }
         _listBox.Visible = true;
         _listBox.BringToFront();
     }



     private void ResetListBox()
     {
         _listBox.Visible = false;
     }

     private void this_KeyUp(object sender, KeyEventArgs e)
     {
         UpdateListBox();
     }

     private void this_KeyDown(object sender, KeyEventArgs e)
     {
         switch (e.KeyCode)
         {
             case Keys.Escape:
                 {
                     if (_listBox.Visible)
                     {
                         ResetListBox();
                         this.Select(this.Text.Length, 0);
                         e.Handled = true;
                     }
                     break;
                 }
             case Keys.Enter:
             case Keys.Tab:
                 {
                     if (_listBox.Visible)
                     {
                         Text = _listBox.SelectedItem.ToString();
                         ResetListBox();
                         _formerValue = Text;
                         this.Select(this.Text.Length, 0);
                         e.Handled = true;
                     }
                     break;
                 }
             case Keys.Down:
                 {
                     if ((_listBox.Visible) && (_listBox.SelectedIndex < _listBox.Items.Count - 1))
                         _listBox.SelectedIndex++;
                     e.Handled = true;
                     break;
                 }
             case Keys.Up:
                 {
                     if ((_listBox.Visible) && (_listBox.SelectedIndex > 0))
                         _listBox.SelectedIndex--;
                     e.Handled = true;
                     break;
                 }


         }
     }

     protected override bool IsInputKey(Keys keyData)
     {
         switch (keyData)
         {
             case Keys.Tab:
                 if (_listBox.Visible)
                     return true;
                 else
                     return false;
             default:
                 return base.IsInputKey(keyData);
         }
     }

     private void UpdateListBox()
     {
         if (Text == _formerValue)
             return;

         _formerValue = this.Text;
         string word = this.Text;

         if (_values != null && word.Length > 0)
         {
             string[] matches = Array.FindAll(_values,
                                              x => (x.ToLower().Contains(word.ToLower())));
             if (matches.Length > 0)
             {
                 ShowListBox();
                 _listBox.BeginUpdate();
                 _listBox.Items.Clear();
                 Array.ForEach(matches, x => _listBox.Items.Add(x));
                 _listBox.SelectedIndex = 0;
                 _listBox.Height = 0;
                 _listBox.Width = 0;
                 Focus();
                 using (Graphics graphics = _listBox.CreateGraphics())
                 {
                     for (int i = 0; i < _listBox.Items.Count; i++)
                     {
                         if (i < 20)
                             _listBox.Height += _listBox.GetItemHeight(i);
                         // it item width is larger than the current one
                         // set it to the new max item width
                         // GetItemRectangle does not work for me
                         // we add a little extra space by using '_'
                         int itemWidth = (int)graphics.MeasureString(((string)_listBox.Items[i]) + "_", _listBox.Font).Width;
                         _listBox.Width = (_listBox.Width < itemWidth) ? itemWidth : this.Width; ;
                     }
                 }
                 _listBox.EndUpdate();
             }
             else
             {
                 ResetListBox();
             }
         }
         else
         {
             ResetListBox();
         }
     }

     public String[] Values
     {
         get
         {
             return _values;
         }
         set
         {
             _values = value;
         }
     }

     public List<String> SelectedValues
     {
         get
         {
             String[] result = Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
             return new List<String>(result);
         }
     }
}
例外フォーム
// form.cs
public partial class ExceptionForm : Form
{
    #region コンストラクタ
    /// <summary>
    /// コンストラクタ
    /// </summary>
    private ExceptionForm()
    {
        InitializeComponent();
    }

    /// <summary>
    /// コンストラクタ
    /// </summary>
    public ExceptionForm(Exception ex) : this()
    {
        this.txtApp.Text = "app-name";
        this.txtDate.Text = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
        this.txtErrorDescription.Text = ex.Message;
        this.txtErrorDetail.Text = ex.StackTrace;
    }
    #endregion

    #region btnClose_Click
    /// <summary>
    /// btnClose_Click
    /// </summary>
    private void btnClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    #endregion
}

// form.Designer.cs
partial class ExceptionForm
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.btnClose = new System.Windows.Forms.Button();
        this.txtErrorDetail = new System.Windows.Forms.TextBox();
        this.tlpError = new System.Windows.Forms.TableLayoutPanel();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.txtApp = new System.Windows.Forms.TextBox();
        this.txtDate = new System.Windows.Forms.TextBox();
        this.txtErrorDescription = new System.Windows.Forms.TextBox();
        this.grpError = new System.Windows.Forms.GroupBox();
        this.tlpError.SuspendLayout();
        this.grpError.SuspendLayout();
        this.SuspendLayout();
        // 
        // btnClose
        // 
        this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.btnClose.Location = new System.Drawing.Point(461, 410);
        this.btnClose.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.btnClose.Name = "btnClose";
        this.btnClose.Size = new System.Drawing.Size(105, 38);
        this.btnClose.TabIndex = 0;
        this.btnClose.Text = "閉じる";
        this.btnClose.UseVisualStyleBackColor = true;
        this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
        // 
        // txtErrorDetail
        // 
        this.txtErrorDetail.BackColor = System.Drawing.SystemColors.Window;
        this.txtErrorDetail.Dock = System.Windows.Forms.DockStyle.Fill;
        this.txtErrorDetail.Location = new System.Drawing.Point(87, 144);
        this.txtErrorDetail.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.txtErrorDetail.Multiline = true;
        this.txtErrorDetail.Name = "txtErrorDetail";
        this.txtErrorDetail.ReadOnly = true;
        this.tlpError.SetRowSpan(this.txtErrorDetail, 2);
        this.txtErrorDetail.ScrollBars = System.Windows.Forms.ScrollBars.Both;
        this.txtErrorDetail.Size = new System.Drawing.Size(464, 216);
        this.txtErrorDetail.TabIndex = 1;
        this.txtErrorDetail.TabStop = false;
        this.txtErrorDetail.WordWrap = false;
        // 
        // tlpError
        // 
        this.tlpError.ColumnCount = 2;
        this.tlpError.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 84F));
        this.tlpError.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        this.tlpError.Controls.Add(this.label1, 0, 0);
        this.tlpError.Controls.Add(this.label2, 0, 1);
        this.tlpError.Controls.Add(this.label3, 0, 2);
        this.tlpError.Controls.Add(this.label4, 0, 4);
        this.tlpError.Controls.Add(this.txtApp, 1, 0);
        this.tlpError.Controls.Add(this.txtDate, 1, 1);
        this.tlpError.Controls.Add(this.txtErrorDescription, 1, 2);
        this.tlpError.Controls.Add(this.txtErrorDetail, 1, 4);
        this.tlpError.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tlpError.Location = new System.Drawing.Point(3, 19);
        this.tlpError.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.tlpError.Name = "tlpError";
        this.tlpError.RowCount = 6;
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F));
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
        this.tlpError.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpError.Size = new System.Drawing.Size(554, 364);
        this.tlpError.TabIndex = 3;
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.label1.Location = new System.Drawing.Point(3, 0);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(78, 30);
        this.label1.TabIndex = 0;
        this.label1.Text = "アプリケーション";
        this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // label2
        // 
        this.label2.AutoSize = true;
        this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
        this.label2.Location = new System.Drawing.Point(3, 30);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(78, 30);
        this.label2.TabIndex = 1;
        this.label2.Text = "発生日時";
        this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
        this.label3.Location = new System.Drawing.Point(3, 60);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(78, 30);
        this.label3.TabIndex = 2;
        this.label3.Text = "エラ-内容";
        this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // label4
        // 
        this.label4.AutoSize = true;
        this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
        this.label4.Location = new System.Drawing.Point(3, 140);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(78, 30);
        this.label4.TabIndex = 3;
        this.label4.Text = "詳細";
        this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // txtApp
        // 
        this.txtApp.BackColor = System.Drawing.SystemColors.Window;
        this.txtApp.Dock = System.Windows.Forms.DockStyle.Fill;
        this.txtApp.Location = new System.Drawing.Point(87, 3);
        this.txtApp.Name = "txtApp";
        this.txtApp.ReadOnly = true;
        this.txtApp.Size = new System.Drawing.Size(464, 23);
        this.txtApp.TabIndex = 4;
        this.txtApp.TabStop = false;
        // 
        // txtDate
        // 
        this.txtDate.BackColor = System.Drawing.SystemColors.Window;
        this.txtDate.Dock = System.Windows.Forms.DockStyle.Fill;
        this.txtDate.Location = new System.Drawing.Point(87, 33);
        this.txtDate.Name = "txtDate";
        this.txtDate.ReadOnly = true;
        this.txtDate.Size = new System.Drawing.Size(464, 23);
        this.txtDate.TabIndex = 5;
        this.txtDate.TabStop = false;
        // 
        // txtErrorDescription
        // 
        this.txtErrorDescription.BackColor = System.Drawing.SystemColors.Window;
        this.txtErrorDescription.Dock = System.Windows.Forms.DockStyle.Fill;
        this.txtErrorDescription.Location = new System.Drawing.Point(87, 64);
        this.txtErrorDescription.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.txtErrorDescription.Multiline = true;
        this.txtErrorDescription.Name = "txtErrorDescription";
        this.txtErrorDescription.ReadOnly = true;
        this.tlpError.SetRowSpan(this.txtErrorDescription, 2);
        this.txtErrorDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
        this.txtErrorDescription.Size = new System.Drawing.Size(464, 72);
        this.txtErrorDescription.TabIndex = 6;
        this.txtErrorDescription.TabStop = false;
        this.txtErrorDescription.WordWrap = false;
        // 
        // grpError
        // 
        this.grpError.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.grpError.Controls.Add(this.tlpError);
        this.grpError.Location = new System.Drawing.Point(12, 12);
        this.grpError.Name = "grpError";
        this.grpError.Size = new System.Drawing.Size(560, 386);
        this.grpError.TabIndex = 4;
        this.grpError.TabStop = false;
        this.grpError.Text = "エラー情報";
        // 
        // ExceptionForm
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.CancelButton = this.btnClose;
        this.ClientSize = new System.Drawing.Size(584, 461);
        this.Controls.Add(this.grpError);
        this.Controls.Add(this.btnClose);
        this.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
        this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.MinimumSize = new System.Drawing.Size(600, 500);
        this.Name = "ExceptionForm";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "エラー画面 - アプリケーションに障害が発生";
        this.tlpError.ResumeLayout(false);
        this.tlpError.PerformLayout();
        this.grpError.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Button btnClose;
    private System.Windows.Forms.TextBox txtErrorDetail;
    private System.Windows.Forms.TableLayoutPanel tlpError;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.GroupBox grpError;
    private System.Windows.Forms.TextBox txtApp;
    private System.Windows.Forms.TextBox txtDate;
    private System.Windows.Forms.TextBox txtErrorDescription;
}
スタートメニュー登録
/// <summary>
/// スタートメニュー登録クラス
/// </summary>
public class StartMenuRegister
{
    #region 変数・プロパティ

    /// <summary>
    /// アプリ名
    /// </summary>
    private string appTitle;
    /// <summary>
    /// 実行ファイル名
    /// </summary>
    private string exeFileName;
    /// <summary>
    /// スクリプトファイル名
    /// </summary>
    private string wshFileName;
    /// <summary>
    /// リンク名
    /// </summary>
    private string lnkFileName;

    #endregion

    #region コンストラクタ
    /// <summary>
    /// コンストラクタ
    /// </summary>
    public StartMenuRegister()
    {
    }
    #endregion

    /// <summary>
    /// 登録
    /// </summary>
    /// <returns>登録結果</returns>
    public bool Regist()
    {
        bool result = true;

        // プロジェクト>プロパティ>アセンブリ情報 で指定した「タイトル」を取得
        var assembly = Assembly.GetExecutingAssembly();
        var attribute = Attribute.GetCustomAttribute(assembly,typeof(AssemblyTitleAttribute)) as AssemblyTitleAttribute;
        this.appTitle = attribute.Title;
        this.exeFileName = Path.GetFileName(Application.ExecutablePath);
        this.wshFileName = Directory.GetParent(Application.ExecutablePath) + "\\addStartup.js";
        this.lnkFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), this.appTitle + ".lnk");




        if (File.Exists(lnkFileName))
        {
            try
            {
                using (StreamWriter w = new StreamWriter(this.wshFileName, false, System.Text.Encoding.GetEncoding("shift_jis")))
                {
                    w.WriteLine("ws = WScript.CreateObject('WScript.Shell');");
                    w.WriteLine("ln = ws.SpecialFolders('Startup') + '\\\\' + '" + this.appTitle + ".lnk';");
                    w.WriteLine("sc = ws.CreateShortcut(ln);");
                    w.WriteLine("sc.TargetPath = ws.CurrentDirectory + '\\\\" + this.exeFileName + "';");
                    w.WriteLine("sc.Save();");
                }

                if (File.Exists(wshFileName))
                {
                    ProcessStartInfo psi = (new ProcessStartInfo());
                    psi.FileName = "cscript";
                    psi.Arguments = @"//e:jscript " + this.wshFileName;
                    psi.WindowStyle = ProcessWindowStyle.Hidden;
                    Process p = Process.Start(psi);

                    p.WaitForExit(10000);
                    File.Delete(this.wshFileName);
                }

                if (!File.Exists(this.lnkFileName))
                {
                    //Logger.Error(ex.ToString());
                    result = false;
                }
            }
            catch (Exception ex)
            {
                result = false;
                //Logger.Error(ex.ToString());
            }
        }

        return result;
    }
}
マクロ

www.atmarkit.co.jp

qiita.com