473,791 Members | 2,725 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Major issue with STAThreading and Clipboard object in vb.net

I have converted a VB6 application to VB.NET. The old application
made extensive use of the Clipboard for copying an Image Name so that
it could be pasted into the image capture app when the user scans the
image. My applications run as compiled assemblies from our Intranet
server and I have setup a Main sub routine in the application with the
following line:

<STAThread()> Public Sub Main()

Note: There is no timer in this application.

Now the main issue is that I still get a threading error when using
the app.
This has occurred in other applications I have created using the same
method in order to have access to the clipboard object. The error
occurrs occasionally, not every time. The consistency is frustrating.

I need a workaround for this method. Is it possible to highlight the
value and send a Ctrl-C to the form or control to put the value on the
clipboard without using the Clipboard.SetDa taObject?

Anyone have any ideas? I would be extremely grateful!!!
Sincerely,

Tim Frawley
Nov 20 '05 #1
9 5954
Hi Tim,

Thanks for posting in the community.

First of all, I would like to confirm my understanding of your issue.
From your description, I understand that when you call the SetDataObject in
an STA console application, you got threading error.
You are working on an STA console application, there is no other thread in
your application.
Have I fully understood you? If there is anything I misunderstood, please
feel free to let me know.

What is the exact error message you got?
Is the object you set to the clipboard a string or an image?

Here is my test code , this is an console application.
You may try to call SetDataObject override function

Places data on the system clipboard and specifies whether the data should
remain on the clipboard after the application exits.
[Visual Basic] Overloads Public Shared Sub SetDataObject(O bject, Boolean)

Imports System.Windows. Forms
Imports System.Drawing
Module Module1
<STAThread()> _
Public Sub Main()
Clipboard.SetDa taObject("Test String", True)
'Dim img As New Bitmap("c:\Wate rlilies.jpg")
'Clipboard.SetD ataObject(img, True)
End Sub
End Module

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #2


Hi Peter,

No, this is not a console application. I have compiled it as a dll
which is loaded via a 'stub' application from our Intranet server.
Esentially it is a windows application distributed via the web.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #3
Hi guys,

This is essentially a smart client application.
Running the application directly will suceed but fail if you deploy. This is
because the exe gets downloaded and run under ieexec process.

This process is running as MTA because there could be many smart client
applications running or other processes under the ieexec. It is also because
the default for .net applications is to be MTA as .net assembles can support
multithreading.

The under lying clipboard processes use COM and the COM object must be
executed in an STA thread.

A normally executed application has an STA thread for its GUI and this is
why a normal application can use the clipboard operations.

OK all interesting but what can you do.
The way I do it is to create a member variable that is a thread.

Where you want to use teh clipboard create a new thread in this variable and
set it to STA. You need to do this because you can not change your current
thread to STA from MTA because it is too late teh thread is already
executing in MTA.

Then do your clipbaord op on that thread.

Note on the form dispose you must check if this thread is active and dispose
it appropriately.

You must also check if it is active before doing another clipboard
operation.

Here is some sample code in C# I posted to the C# group on this

Please note this is a summary version of my code. Error handling and cleanup
in the main dispose etc are required.

I use two functions one to invoke the thread
=============== =============== =============== ===============
private void CopyMenu_Click( object sender, System.EventArg s e)

{

if (th != null)

if (th.IsAlive)

th.Abort();

th = new Thread(new ThreadStart(Cop ySTA));

th.ApartmentSta te = ApartmentState. STA ;

th.Start();

}

=============== =============== =============== ===============
And the other is called by the thread

[STAThread]

private void CopySTA()

{

Clipboard.SetDa taObject(this.t extBox1.Text);

Thread.CurrentT hread.Join();

}

=============== =============== =============== ===============

Hope this helps
Daryl
"Tim Frawley" <ti*********@fi shgame.state.ak .us> wrote in message
news:OS******** ******@TK2MSFTN GP10.phx.gbl...


Hi Peter,

No, this is not a console application. I have compiled it as a dll
which is loaded via a 'stub' application from our Intranet server.
Esentially it is a windows application distributed via the web.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 20 '05 #4
Hi Tim,

Thanks for your quickly reply!

I have made a test, this is my test result.
1. I make a stub application as below, I will test to run the application
by using the URL
http://website/TestStub.exe

[TestStub.exe]
Imports System.Reflecti on
Imports System.Windows. Forms
Module Module1
<STAThread()> _
Sub Main()
Dim SampleAssembly As [Assembly]
SampleAssembly =
[Assembly].LoadFrom("http ://website/TesSmartClient. dll")
' Obtain a reference to a method known to exist in assembly.
Dim tp As Type = SampleAssembly. GetTypes()(0)
Dim o As Object =
SampleAssembly. CreateInstance( "TesSmartClient .Form1")
o.GetType().Inv okeMember("Show ", BindingFlags.In vokeMethod,
Nothing, o, New Object() {})
Application.Run (o)
End Sub
End Module

2. I make windows form dll application to access the local machine
clipboard.
[TesSmartClient. dll]

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
MsgBox(Threadin g.Thread.Curren tThread.Apartme ntState.ToStrin g())
'I get the thread ApartmentState STA
End Sub

Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button2.Click
Dim str As String = "Hello World"
Clipboard.SetDa taObject(str, True)
End Sub

Private Sub Button3_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button3.Click
' Declares an IDataObject to hold the data returned from the
clipboard.
' Retrieves the data from the clipboard.
Dim iData As IDataObject = Clipboard.GetDa taObject()

' Determines whether the data is in a format you can use.
If iData.GetDataPr esent(DataForma ts.Text) Then
' Yes it is, so display it in a text box.
MsgBox(CType(iD ata.GetData(Dat aFormats.Text), String))
Else
' No it is not.
MsgBox("Could not retrieve data off the clipboard.")
End If
End Sub

Is this your senario?
If yes, please test my code to see if the problem persists.

If no can you describe your senario more detailed and post the exactly
error messge your got, because I can not reproduce the problem on my side

My test environment is windows XP+SP1 VS.NET2003 + NET framework 1.1.

To isolate the problem, I suggest you run the application as an
administrator, and run the smartclient(run in IE browser) from the
localhost to make a test.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #5


I notice that you are STAThreading your stub which is not something that
I was doing. I will test that out.

My method for loading the assembly is a little different, primarily I do
not have all the arguments that you have in your test. Here is a sample
of what I am doing.

Select Case strApp
Case "SI"
strAssembly = "ScaleInput.dll "
strAssemblyForm = "ScaleInput.frm Input"
Case "SM"
strAssembly = "ScaleImport.dl l"
strAssemblyForm = "ScaleImport.fr mImport"
Case "SG"
strAssembly = "ScaleImage.dll "
strAssemblyForm = "ScaleImage.frm ScaleImage"
End Select
Dim formAsm As [Assembly]
Dim formtype As Type
Dim FormObj As Object
Dim Form1 As Form

formAsm = [Assembly].LoadFrom(gstrA ssemblyLocation & strAssembly)
formtype = formAsm.GetType (strAssemblyFor m)
FormObj = Activator.Creat eInstance(formt ype)
Form1 = CType(FormObj, Form)
Form1.ShowDialo g()
I am using the stub to load multiple possible applications via command
line arguments passed via the hyperlink. This way I can tell the stub
which app to load, weather to load in test mode, etc. I use property
assignments in the assembly to fill the values. In one of our apps we
set the connection string to the database in this manner.

In any case, your methods are the same but the number of arguments is
different. Mine seems a little streamlined but I do not know what all
the arguments are for. I only know that this works. :)

I will play around with your test and see what comes of it.

Thanks for helping me out Peter!

Tim

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #6
Hi Tim,

Based on my test, by deafult the thread apartment of [TestStub.exe] will be
<STAThread()> . And if we specify it to MTAThread we will get error when
access to the clipboard.

I think you code seems to be similar with my testcode. I look forward to
hearing from you after you have a test with my code.
Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #7
Currently my app is STAThread in the Sub Main of the assembly that uses
the Clipboard.SetDa taOjbect method as shown here:
Module modBase

<STAThread()> Public Sub Main()
Try
Application.Run (New frmScaleImage)
Catch ex As Exception
Dim strError As String
If gblnTEST_MODE Then
strError = "TESTMODE: frmInput.Main() "
Else
strError = "frmInput.Main( )"
End If
WriteToEventLog (strError, ex.ToString)
MsgBox("An unexpected application error has occurred." &
vbCrLf & vbCrLf & _
"Please leave this message on the screen and
call a programmer." & _
strError & vbCrLf & vbCrLf & ex.ToString)
End Try
End Sub

My Catch didn't 'catch' this error either.

The app worked fine today for a while but just now blew up. This is why
I am saying that the consistency if frustrating.

This is the error I got today when using the app:

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Threadin g.ThreadStateEx ception: The current thread must set to
Single Thread Apartment (STA) mode before OLE calls can be made. Ensure
that your Main function has STAThreadAttrib ute marked on it.
at System.Windows. Forms.Clipboard .SetDataObject( Object data, Boolean
copy)
at System.Windows. Forms.Clipboard .SetDataObject( Object data)
at ScaleImage.frmS caleImage.tdbgD ata_Click(Objec t sender, EventArgs
e)
at System.Windows. Forms.Control.O nClick(EventArg s e)
at C1.Win.C1TrueDB Grid.BaseGrid.F rame.OnClick(Ev entArgs e)
at System.Windows. Forms.Control.W mMouseUp(Messag e& m, MouseButtons
button, Int32 clicks)
at System.Windows. Forms.Control.W ndProc(Message& m)
at C1.Win.C1TrueDB Grid.C1TrueDBGr id.WndProc(Mess age& m)
at System.Windows. Forms.ControlNa tiveWindow.OnMe ssage(Message& m)
at System.Windows. Forms.ControlNa tiveWindow.WndP roc(Message& m)
at System.Windows. Forms.NativeWin dow.Callback(In tPtr hWnd, Int32 msg,
IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/microsoft.net/framework/v1.1.4322/mscorlib.dll
----------------------------------------
System.Drawing
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/system.drawing/1.0.5000.0__b03 f5f7f11d50
a3a/system.drawing. dll
----------------------------------------
System
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/system/1.0.5000.0__b77 a5c561934e089/syst
em.dll
----------------------------------------
RegexAssembly8_ 0
Assembly Version: 0.0.0.0
Win32 Version: n/a
CodeBase:
----------------------------------------
IEExecRemote
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/ieexecremote/1.0.5000.0__b03 f5f7f11d50a3
a/ieexecremote.dl l
----------------------------------------
Stub
Assembly Version: 1.0.1525.15805
Win32 Version: n/a
CodeBase: http://intranet.taglab.org/TMR/ScaleApps/Stub.EXE
----------------------------------------
System.Windows. Forms
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/system.windows. forms/1.0.5000.0__b77 a5c5
61934e089/system.windows. forms.dll
----------------------------------------
System.Xml
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/system.xml/1.0.5000.0__b77 a5c561934e089/
system.xml.dll
----------------------------------------
Microsoft.Visua lBasic
Assembly Version: 7.0.5000.0
Win32 Version: 7.10.3052.4
CodeBase:
file:///c:/windows/assembly/gac/microsoft.visua lbasic/7.0.5000.0__b03 f5f
7f11d50a3a/microsoft.visua lbasic.dll
----------------------------------------
ScaleImage
Assembly Version: 1.1.1525.25632
Win32 Version: n/a
CodeBase: http://intranet.taglab.org/TMR/ScaleApps/ScaleImage.DLL
----------------------------------------
C1.Win.C1TrueDB Grid
Assembly Version: 1.2.20033.30829
Win32 Version: 1.2.20034.31024
CodeBase:
file:///c:/windows/assembly/gac/c1.win.c1truedb grid/1.2.20033.30829 __75a
e3fb0e2b1e0da/c1.win.c1truedb grid.dll
----------------------------------------
System.Data
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/system.data/1.0.5000.0__b77 a5c561934e089
/system.data.dll
----------------------------------------
C1.Common
Assembly Version: 1.0.20031.116
Win32 Version: 1.0.20031.117
CodeBase:
file:///c:/windows/assembly/gac/c1.common/1.0.20031.116__ e272bb32d11b194
8/c1.common.dll
----------------------------------------
Accessibility
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.573
CodeBase:
file:///c:/windows/assembly/gac/accessibility/1.0.5000.0__b03 f5f7f11d50a
3a/accessibility.d ll
----------------------------------------

************** JIT Debugging **************
To enable just in time (JIT) debugging, the config file for this
application or machine (machine.config ) must have the
jitDebugging value set in the system.windows. forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuratio n>
<system.windows .forms jitDebugging="t rue" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the machine
rather than being handled by this dialog.


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #8


I just implemented <STAThread()> on the Stub as well and still received
the error.

Uhg....


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #9
Hi Tim,

Thanks for posting in the community.

Yes, when the application.run is in the try---catch block, the catch
statement will not catch the exception.
Here is a link may help you.
http://groups.google.com/groups?q=ap...g-shen+yu%22&h
l=zh-CN&lr=&ie=UTF-8&oe=UTF-8&selm=TxRqBsd2 DHA.3532%40cpms ftngxa07.phx.gb l&r
num=1

To further troubleshoot the problem, I suggest you try my test code first
to see if the problem persists. This will help us to know if the problem is
about the coding of your dll, or the environment of your machine.

I will appreciate your efforts that you can make a test with the demo I
post previously and let me know the result.

If my demo works for you, please add code based on my demo to see what
cause the problem. From the error message, I think the problem may be
caused by when you access the clipboard, the thread apartment will changed
to MTA, which cause the problem. So please add event log before each method
invoke to trace when the ThreadApartment state was changed to MTA.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
11478
by: LG | last post by:
Just have a question with regards to the clipboard, and how to read what other applications (Adobe InDesignCS) place in the clipboard. I am currently in the process of creating a booklet from a database, and I need the data to be laid out in a tabular format, and set out in a specific way. At the current point in time, I am copy/pasting the raw text from the database into a table layout in InDesign. What I was thinking is that if I could...
5
4079
by: TC | last post by:
Hello, Here is what I'm trying to do: -- Make sure both MS Excel and MS Word are running -- Create an Excel chart -- Save the Excel file -- Copy the Excel chart onto the clipboard using Ctrl + C -- Go to Word and look under Edit > Paste Special -- Note there is a source reference and an option to paste the chart as a
2
1680
by: Sunny | last post by:
Hi I am using Data Objects in my Applications and need to clear the ClipBoard or Memory Buffer after some intervals How do i clear the contents of the System.ClipBoard With Regard Sunny
1
3246
by: keith | last post by:
I read a book, Programming Microsoft WINDOWS with C# by Charles Petzold, which shows ho to set or get string and image to and from Clipboard. It says even a button object can be set or go to and from a Clipboard I defined a class, e.g public class AB string s int i
3
1722
by: keith | last post by:
I can use following codes to set and get object (serializable class) from Clipboar Clipboard.SetDataObject(obj) then DataObject data=new DataObject() obj=(ClassType)data.GetData(typeof(ClassType))
4
9194
by: Wayne Wengert | last post by:
I have an aspx page on which I am trying to copy the contents of a textbox to the client clipboard when the users clicks a button. The button code is as follows: ===================================== Private Sub btnCopyToClipboard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopyToClipboard.Click Clipboard.SetDataObject(txtHidden.Text) End Sub
2
3265
by: Shayne H | last post by:
I am trying to write a method to copy some text to the clipboard, and leave a copy of it there after the application has exited. Sub CopyToClipboard(ByVal value As Object) Dim data As New DataObject() data.SetData(DataFormats.UnicodeText, True, value) Clipboard.SetDataObject(data,True) End Sub When I test it, I get an exception:
5
21038
by: DraguVaso | last post by:
Hi, I'm looking for a way to Copy and Paste Files to the clipboard. I found a lot of articles to copy pieces of text and bitmaps etc, but nog whole files. Whay I need is like you have in windows explorer: when you do a right-click on a file and choose Copy, and than paste it somewhere in my application and vice versa.
0
1310
by: =?Utf-8?B?UGV0ZQ==?= | last post by:
This is a duplicate of a posting on Officedev so apologies to anyone who's read this already. I had an Office add-in built in VB.Net 2003 with an Excel and a Word add-in class that transferred data from Excel to Word using the clipboard. It worked well until I developed a new version using VS 2005 and VSTO (the Excel and Word add-ins are now separate DLLs). Now I find that after placing data on the clipboard using the Excel.Range.Copy...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10154
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3713
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2913
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.