SyntaxHighlighter

2013-10-28

SyntaxHighlighter

Official Site: http://alexgorbatchev.com/SyntaxHighlighter/

for on-line offer http://alexgorbatchev.com/SyntaxHighlighter/hosting.html

Add the below codes into template's HEAD tag

<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/3.0.83/styles/shThemeDefault.css" />
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js"></script>
<!-- Add Brush Here -->
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js"></script>
   
<script type="text/javascript"> 
  SyntaxHighlighter.all();
</script>

Usage:
<pre class="brush:csharp"> int a=2;</pre>

will be show as:
 int a=2; 


[C#]Centering a Message Box on the Active Window

There are 2 way to centering the default MessageBox
or said, 1 only way, and 2 kind of Invoking.

1. Make a new WindowForm who has centerParent Location, then copy it's location to the MessageBox by "Hook" the system dialog's location.
2. Just Hook the system dialog's location and set it before call MessageBox.Show()

Way 1: CenterWinDialog by Hans Passant

There's the code(class CenterWinDialog):
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CenterWinDialog : IDisposable {
    private int mTries = 0;
    private Form mOwner;

    public CenterWinDialog(Form owner) {
        mOwner = owner;
        owner.BeginInvoke(new MethodInvoker(findDialog));
    }

    private void findDialog() {
        // Enumerate windows to find the message box
        if (mTries < 0) return;
        EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
        if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) {
            if (++mTries < 10) mOwner.BeginInvoke(new MethodInvoker(findDialog));
        }
    }
    private bool checkWindow(IntPtr hWnd, IntPtr lp) {
        // Checks if <hwnd> is a dialog
        StringBuilder sb = new StringBuilder(260);
        GetClassName(hWnd, sb, sb.Capacity);
        if (sb.ToString() != "#32770") return true;
        // Got it
        Rectangle frmRect = new Rectangle(mOwner.Location, mOwner.Size);
        RECT dlgRect;
        GetWindowRect(hWnd, out dlgRect);
        MoveWindow(hWnd,
            frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) / 2,
            frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) / 2,
            dlgRect.Right - dlgRect.Left,
            dlgRect.Bottom - dlgRect.Top, true);
        return false;
    }
    public void Dispose() {
        mTries = -1;
    }

    // P/Invoke declarations
    private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
    [DllImport("user32.dll")]
    private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentThreadId();
    [DllImport("user32.dll")]
    private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
    [DllImport("user32.dll")]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int w, int h, bool repaint);
    private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
}

Usage:
    private void button1_Click(object sender, EventArgs e) {
        using (new CenterWinDialog(this)) {
            MessageBox.Show("Nobugz waz here");
        }
    }


Way 2: MessageBoxHelper by Jason Carr

There's the code(class MessageBoxHelper):
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal static class MessageBoxHelper
{
    internal static void PrepToCenterMessageBoxOnForm(Form form)
    {
        MessageBoxCenterHelper helper = new MessageBoxCenterHelper();
        helper.Prep(form);
    }

    private class MessageBoxCenterHelper
    {
        private int messageHook;
        private IntPtr parentFormHandle;

        public void Prep(Form form)
        {
            NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
            GCHandle.Alloc(callBackDelegate);

            parentFormHandle = form.Handle;
            messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
        }

        private int CenterMessageCallBack(int message, int wParam, int lParam)
        {
            NativeMethods.RECT formRect;
            NativeMethods.RECT messageBoxRect;
            int xPos;
            int yPos;

            if (message == 5)
            {
                NativeMethods.GetWindowRect(parentFormHandle, out formRect);
                NativeMethods.GetWindowRect(new IntPtr(wParam), out messageBoxRect);

                xPos = (int)((formRect.Left + (formRect.Right - formRect.Left) / 2) - ((messageBoxRect.Right - messageBoxRect.Left) / 2));
                yPos = (int)((formRect.Top + (formRect.Bottom - formRect.Top) / 2) - ((messageBoxRect.Bottom - messageBoxRect.Top) / 2));

                NativeMethods.SetWindowPos(wParam, 0, xPos, yPos, 0, 0, 0x1 | 0x4 | 0x10);
                NativeMethods.UnhookWindowsHookEx(messageHook);
            }

            return 0;
        }
    }

    private static class NativeMethods
    {
        internal struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        internal delegate int CenterMessageCallBackDelegate(int message, int wParam, int lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool UnhookWindowsHookEx(int hhk);

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

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

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern IntPtr SetWindowsHookEx(int hook, CenterMessageCallBackDelegate callback, IntPtr hMod, int dwThreadId);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    }
}


Usage:
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBoxHelper.PrepToCenterMessageBoxOnForm(this);
        MessageBox.Show("Hello!", "Hello!", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0);
    }

[C#] Custom Dialog Form and Control the DialogResult's value

You can customize any windows form to be a dialog form, with setting the below properties:
Property NameValueNote
FormBorderStyleFixed Dialog
MinimizeBoxFalse
MaximizeBoxFalse
ControlBoxFalse
TopmostTrueOption. To set it if you want the dialog be the most top one even there is other windows programs. Maybe you will like to return it off in most time.
ShowIconFalseWhen use this option, remember to sets ShowInTaskbar to false,too.
As Tod's advice, he leave this true and topmost to false, so the user can switches to another program and get back to this from taskbar.
ShowInTaskbarFalseTo 'hidden' the program from Taskbar.
CancelButtonThe Button object's nameAnd the Button object's property DialogResult will be set to Cancel, too.
StartPositionCenterParent




For set the dialog's DialogResult, you can set it into a button's action or a custom method with
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;

or just set the button's DialogResult property to the value you want to return.

REMEMBER to call the form with ShowDialog() not Show().

2013-10-25

[C#]Force DataGridView Save Current Row's Data to Backyard.

Usually we edit the table data with DataGridView.

I do it, too. and I get problem when I try to get the changed DataTable.

It happened if you try to save data just after editing it.


There is the situation:

I have a 3x3 DataTable dt, and I link it to a DataGridView dgv
dgv.DataSource = dt;

then I edited the content with row 3 column 3.
I can move cursor to column 1 or column 2, but before i move cursor to the other row, the changing of row 3 will not be set to DataTable.

It's not good. I want it be saved after click SAVE or Ctrl-S.

So, there is a solution: DataGridView.EndEdit().
but, the row's data didn't change with only DataGridView.EndEdit().
The CurrentRow must lose focus to save the data.
Hmm... Here is a member called CurrentCell
and Someone set CurrentCell to null, then the data is stored.

I tried it, and it works good!
so, if you want to save the current row's data.
run the below 2 statement:

dgv.EndEdit();
dgv.CurrentCell = null;

then the current row's change will be saved in to DataTable, too.


[C#]Get DataTable from Database, Update DataTable to Database

just take a note.

When we want to update database with a list, as you know, there will be 3 kinds of operation: insert(for new rows), update(for changed rows), delete(for deleted rows)

for a single record, it will be easy. But for a list of data, it will be a nightmare.

use the .NET DataAdapter, we can make it easier.
for base, we have sqlConnectString for default connection, and we try to access all columns of demoTable. There is a global DataTable named dt.

to make the example for common case, I will type it for SQL server.

1. to get DataTable from Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    using(var cmd = new SQLCommand(conn))
    {
        cmd.CommandText = sql;
        var reader = cmd.ExecuteReader();
        dt.Load(reader);
    }
}
2. to update DataTable's data to Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    var adp = new SQLDataAdapter(sql, conn);
    var cmb = new SQLCommandBuilder(adp);
    adp.Update(dt);
}

to speed up the database access, can add transaction commands. Begin the transaction before update, and commit the transaction after update.

人気の投稿