Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Tip/Trick

Implement Copy Paste C# Code

Rate me:
Please Sign up or sign in to vote.
3.89/5 (15 votes)
24 Feb 2016CPOL2 min read 65.3K   41   9
Guide on how to create generic Clipboard manager in C#. Implement Copy Paste C# code, download the full source code.

Introduction

It is easy to implement Copy Paste operations using C# code.

First, you need to make the class that you want to put into clipboard- serializable.

[Serializable]
    public class ClipBoardTestCase
    {
        public ClipBoardTestCase(List<TestCase> testCases, ClipBoardCommand clipBoardCommand)
        {
            this.TestCases = testCases;
            this.ClipBoardCommand = clipBoardCommand;
        }

        public List<TestCase> TestCases { get; set; }

        public ClipBoardCommand ClipBoardCommand { get; set; }
    }

ClipBoardCommand is a simple enum with three values: Copy, Cut, None. We are going to use it later in the paste operation to determine if the clip should be removed from the clipboard.

Also, make sure that your class is serializable, add the [Serializable] attribute to it. If you are working with system objects, be sure that all of them can be serialized. I have noticed that some of the core TFS objects are not. If that is the case, just add a [NonSerialized] attribute to them.

Serialization Tester

Also, you can use the following method to test if the properties and variables of your class can be serialized.

public static bool IsSerializable(object obj)
{
    MemoryStream mem = new MemoryStream();
    BinaryFormatter bin = new BinaryFormatter();
    try
    {
        bin.Serialize(mem, obj);
        return true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Your object cannot be serialized." +
                         " The reason is: " + ex.ToString());
        return false;
    }
}

Implement Copy Paste C# Serialization Manager

I have created a reusable generic class for the basic clipboard actions; you can use it directly.

public class ClipBoardManager<T> where T : class
    {
        public static T GetFromClipboard()
        {
            T retrievedObj = null;
            IDataObject dataObj = Clipboard.GetDataObject();            
            string format = typeof(T).FullName;
            if (dataObj.GetDataPresent(format))
            {
                retrievedObj = dataObj.GetData(format) as T;                
            }
            return retrievedObj;
        }

        public static void CopyToClipboard(T objectToCopy)
        {
            // register my custom data format with Windows or get it if it's already registered
            DataFormats.Format format = DataFormats.GetFormat(typeof(T).FullName);

            // now copy to clipboard
            IDataObject dataObj = new DataObject();
            dataObj.SetData(format.Name, false, objectToCopy);
            Clipboard.SetDataObject(dataObj, false);
        }

        public static void Clear()
        {
            Clipboard.Clear();
        }
    }

The usage is simple. Just initialize your object and pass it to the manager's method.

ClipBoardCommand clipBoardCommand = isCopy ? ClipBoardCommand.Copy : ClipBoardCommand.Cut;
ClipBoardTestCase clipBoardTestCase = new ClipBoardTestCase(testCases, clipBoardCommand);
ClipBoardManager<ClipBoardTestCase>.CopyToClipboard(clipBoardTestCase);

When you are performing cut operations, you need to remove the last clip from the clipboard or clear it all. So you can use the ClipBoardCommand enum to do it.

Task t = Task.Factory.StartNew(() =>
            {
                TestSuiteManager.PasteTestCasesToSuite(suiteToPasteIn.Id, clipBoardTestCase);
            });
            t.ContinueWith(antecedent =>
            {
                if (clipBoardTestCase.ClipBoardCommand.Equals(ClipBoardCommand.Cut))
                {
                    System.Windows.Forms.Clipboard.Clear();
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());

If you need to add more logic to your clipboard manager, you can visit the official MSDN documentation here.

So Far in the C# Series

  1. Implement Copy Paste C# Code
  2. MSBuild TCP IP Logger C# Code
  3. Windows Registry Read Write C# Code
  4. Change .config File at Runtime C# Code
  5. Generic Properties Validator C# Code
  6. Reduced AutoMapper- Auto-Map Objects 180% Faster
  7. 7 New Cool Features in C# 6.0
  8. Types Of Code Coverage- Examples In C#
  9. MSTest Rerun Failed Tests Through MSTest.exe Wrapper Application
  10. Hints For Arranging Usings in Visual Studio Efficiently
  11. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 1
  12. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 2
  13. Specify Assembly References Based On Build Configuration in Visual Studio
  14. Top 15 Underutilized Features of .NET
  15. Top 15 Underutilized Features of .NET Part 2
  16. Neat Tricks for Effortlessly Format Currency in C#
  17. Assert DateTime the Right Way MSTest NUnit C# Code
  18. Which Works Faster- Null Coalescing Operator or GetValueOrDefault or Conditional Operator
  19. Specification-based Test Design Techniques for Enhancing Unit Tests
  20. Get Property Names Using Lambda Expressions in C#
  21. Top 9 Windows Event Log Tips Using C#

If you enjoy my publications, feel free to SUBSCRIBE.
Also, hit these share buttons. Thank you!

Source Code

The post- Implement Copy Paste C# VB .NET Application appeared first on Automate The Planet.

All images are purchased from DepositPhotos.com and cannot be downloaded and used for free.
License Agreement

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

 
QuestionHow to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
SachinSutar2-Oct-17 23:15
SachinSutar2-Oct-17 23:15 
AnswerRe: How to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
Anton Angelov21-Oct-17 5:51
Anton Angelov21-Oct-17 5:51 
GeneralRe: How to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
SachinSutar22-Oct-17 23:16
SachinSutar22-Oct-17 23:16 
GeneralRe: How to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
Anton Angelov22-Oct-17 23:37
Anton Angelov22-Oct-17 23:37 
GeneralRe: How to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
SachinSutar22-Oct-17 23:54
SachinSutar22-Oct-17 23:54 
GeneralRe: How to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
Anton Angelov22-Oct-17 23:58
Anton Angelov22-Oct-17 23:58 
You can check the source code of the app that I told you about. [^]
Here you can find the XAML of one of the views. Here I have created bindings with shortcuts like ctrl + C where the copy command is executed. Look into the code behind as well.
GeneralMy vote of 5 Pin
Farhad Reza15-Nov-16 8:37
Farhad Reza15-Nov-16 8:37 
QuestionVisual Studio Project? Pin
Member 111225545-Mar-15 4:58
Member 111225545-Mar-15 4:58 
AnswerRe: Visual Studio Project? Pin
Anton Angelov5-Mar-15 7:50
Anton Angelov5-Mar-15 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.