Click here to Skip to main content
13,191,642 members (63,362 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

25.9K views
41 bookmarked
Posted 21 Feb 2015

Implement Copy Paste C# Code

, 24 Feb 2016
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Anton Angelov
CEO Automate The Planet
Bulgaria Bulgaria
Anton Angelov is an IT Consultant and Quality Assurance Architect at Innovative Lab. He is passionate about automation testing and designing test harness and tools, having the best industry development practices in mind. In addition, he is an active blogger and the founder of Automate The Planet. He strives to make the site one of the leading authorities in Automation Testing by presenting compelling articles, inspiring ardent discussions amongst the community. He is also one of the most-rated-answer authors of questions about Test Automation Frameworks (WebDriver) on Stack Overflow.

You may also be interested in...

Pro

Comments and Discussions

 
QuestionHow to Copy and paste multiple controls (textbox, combobox etc..) ? Pin
SachinSutar2-Oct-17 23:15
memberSachinSutar2-Oct-17 23:15 
GeneralMy vote of 5 Pin
Forhad Reza15-Nov-16 8:37
memberForhad Reza15-Nov-16 8:37 
QuestionVisual Studio Project? Pin
Member 111225545-Mar-15 4:58
memberMember 111225545-Mar-15 4:58 
AnswerRe: Visual Studio Project? Pin
Anton Angelov5-Mar-15 7:50
professionalAnton 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171017.2 | Last Updated 25 Feb 2016
Article Copyright 2015 by Anton Angelov
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid