[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1040
  • Last Modified:

Winform -Textbox to MSWord (vb.net)

Hi Experts,

I'm trying to export text from Textbox, then open MSWord and it auto pastes... but this code doesn't paste :(

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim proc As Process = Process.Start("winword.exe")

        ' Wait a short while for Notepad to fully launch.
        System.Threading.Thread.Sleep(250)

        ' Copy the data from the multi-line textbox into the clipboard.
        Clipboard.SetDataObject(Me.TextBox1.Text)

        ' Send a Ctrl-V to Notepad to paste the data from the clipboard into the text editor.
        SendKeys.Send("^v")

    End Sub

Open in new window

0
RobertoFreemano
Asked:
RobertoFreemano
  • 6
  • 3
  • 3
2 Solutions
 
Jacques Bourgeois (James Burger)Commented:
Sendkeys is awkward to use because it sends the keys to any application that is active, so you never know where it will end up.

I do not think that a quarter of a second is long enough for Word to start, so your application is probably the one that receives the Ctrl-V. Finding the right delay is almost impossible. It might change from one computer to another, and even on the same computer because of anything that could be running in the background while the application is running.

Combining Process.Start, Sleep and SendKeys might be the first idea that comes to mind, but you are simply using 3 differents methods that, combined together, will give very irregular results.

You should control Word instead, by first adding it to the References of your project, and then use code such as the following (not tested, Word is not installed on the computre form which I am writing).

Dim app As New Microsoft.Office.Interop.Word.Application

app.Visible = True
app.Documents.Add
app.Selection.TypeText (Me.TextBox1.Text)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Totally agreed.

If you absolutely need to use the SendKeys route, though, then something like this ~may~ work better:
Public Class Form1

    Private Const SW_SHOWNORMAL As Integer = 1

    Private Declare Function IsIconic Lib "user32" (ByVal handle As Integer) As Integer
    Private Declare Function ShowWindow Lib "user32" (ByVal handle As IntPtr, ByVal nCmdShow As Integer) As Integer
    Private Declare Function SetForegroundWindow Lib "user32" (ByVal handle As IntPtr) As Integer

    Private Sub FocusApp(ByVal FullPathExeName As String)
        Dim processes() As Process = Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(FullPathExeName))
        If processes.Length = 0 Then
            Dim P As Process = Process.Start(FullPathExeName)
            P.WaitForInputIdle()
        Else
            ' Restore the window if it is minimized...
            If IsIconic(processes(0).MainWindowHandle) <> 0 Then
                ShowWindow(processes(0).MainWindowHandle, SW_SHOWNORMAL)
            End If

            ' Make it the foreground window...
            SetForegroundWindow(processes(0).MainWindowHandle)
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        FocusApp("winword.exe")

        ' Copy the data from the multi-line textbox into the clipboard.
        Clipboard.SetText(Me.TextBox1.Text)

        ' Send a Ctrl-V to paste the data from the clipboard.
        SendKeys.Send("^v")
    End Sub

End Class

Open in new window


As James states, though, using SendKeys is a finicky solution and may even need tweaking for each individual application it is used with...
0
 
RobertoFreemanoAuthor Commented:
Hi James,

I tried your method but had few issues... I think it might just be finding the correct references to support it.
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
RobertoFreemanoAuthor Commented:
Hi Mike,

Works a treat; however, sorry to be a pain in the bum... I wrote this ticket in work where we use MS Word, and it rightly states in the ticket summary... but I'm home and I have OpenOffice.  I wonder if you could offer some advice.

I changed a line of code to
FocusApp("swriter.exe")

Open in new window

and OpenOffice Writer opens, but no text :(

Also,
Is there a MS cleanup process to release the resource so my vb app continues to work?

Thanks,
Roberto
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Haha!...see my last comment:

    "As James states, though, using SendKeys is a finicky solution and may even need tweaking for each individual application it is used with..."

There is no foolproof solution when using SendKeys.  You'd either have to add a delay and live with that, or us a "directed" solution which sends keystrokes directly to a window handle.  With that approach, though, you lose the generic approach is it will only work with that specific application.

What is your app really doing?...the "big picture"?
0
 
RobertoFreemanoAuthor Commented:
I'm working on a Text Editor (to get me started when writing my Books)... I know what you're thinkning already - "Are you crazy, just use Msword or something else..."

You've already helped me develop the app, to a point were it's 99% ready... I raised another question earlier (still open ~ http://www.experts-exchange.com/Programming/Languages/.NET/Q_27859740.html) regarding spell checker...

I fear this is getting me nowhere fast, so I decided to be cheeky and use another app to spell check for me!
0
 
RobertoFreemanoAuthor Commented:
As i plan to write a little in the office and then at home... the need to get my local word~processor to spell check will change.
0
 
Jacques Bourgeois (James Burger)Commented:
You will never be able to control Word and OpenOffice, or any 2 applications for that matter, with the same code, no matter if you use SendKeys or control them directly as I suggested.

2 different applications will open in different ways, have different shortcuts, react in different ways when you do a given operation in both.

You need to target one application, and work for that one. If you develop an application for users that have Word in their environment, then code for Word and nothing else. If you bring your job at home, work on it on OpenOffice, then you are losing your time because it won't work when you bring it back in an environment where they use Word.
0
 
RobertoFreemanoAuthor Commented:
Ok, I'm happy with that explanation... thanks Guys... just one more thing... how do I release word, after it's opened? My VB app hangs if word is still open ;)

Thanks,
Roberto
0
 
Jacques Bourgeois (James Burger)Commented:
Basically, you call Quit on the Word.Application object.

But there is no definitive way to do it, there are many variations. That depends on what you are doing while you are controlling Word.

You might need to Save the Document object before Quitting.

If you do not want Word to close, simply set your Application object to Nothing.

If you find out that Word still runs in the background as a Process, you might need to call ReleaseComObject on your objects after quitting.

.NET and Word live in 2 different words, so making them work together is sometimes harder that living in a completely .NET or a completely COM (Word is a COM application) environment.
0
 
RobertoFreemanoAuthor Commented:
Thanks Guys
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now