Saturday, May 25, 2013

My First C# Utility: Clipboard Text to VB or C# String

Well, my C# skills have now progressed a step beyond "Hello World!". I just compiled a little C# executable to eliminate the drudgery of converting long SQL statements into multi-line code strings. Can't you just see me as the code monkey version of the harried housewife in those old Calgon ads, working my fingers to the bone in Visual Studio and finally throwing up my hands in frustration? Then the voiceover guy comes in with a smooth expo of my utility...

Anyway, the logic was trivial, but I did it in C# as an exercise, so it took a few hours instead of a few minutes. I suppose that, six months ago, contorting my VB head to fit the contours of C# would have seemed taxing, but during that time I've accomplished the much more difficult task of contorting my poor application developer brain around set-based database logic. Now translating from VB to C# doesn't seem that bad.

I got it working, compiled it, and created two desktop shortcuts to the same executable.


In addition to renaming each shortcut, I modified its properties so that each one sends the appropriate command line argument to the executable, and each one runs via a combination of control keys regardless of where I am in Windows.

The upshot is that I can go from this... this...

...or this... about a second, with a quick CTRL+C, CTRL+ALT+V + CTRL+V for VB, or CTRL+C, CTRL+ALT+C, CTRL+V for C#.

I has a happy. Colon. End paren.

Here's the code. Use it, critique it, print it and wear it as a hat. Y'know. If you're into that sort of thing.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
    public partial class frmClipToCode : Form
        public frmClipToCode()

        private void Form1_Load(object sender, EventArgs e)
            // Takes the selected text from a text box and puts it on the clipboard. 


            // Declares an IDataObject to hold the data returned from the clipboard. 
            // Retrieves the data from the clipboard.
            IDataObject iData = Clipboard.GetDataObject();

            // Determines whether the data is in a format you can use. 
            if (iData.GetDataPresent(DataFormats.Text))
                string sOriginalText = (String)iData.GetData(DataFormats.Text);
                string sArg = Environment.GetCommandLineArgs()[1];
                string sLineContinuationChars = @" "" & _";
                if (!sArg.Equals("VB", StringComparison.OrdinalIgnoreCase))
                    sLineContinuationChars = @" "" + ";

                Clipboard.SetDataObject(@""" " + sOriginalText.Replace(Environment.NewLine, sLineContinuationChars + Environment.NewLine + @""" ") + @" """, true);
                MessageBox.Show("No text in clipboard.");

No comments: