[API]
RtlMoveMemory
WideCharToMultiByte
CloseHandle

[INCLUDE]
CharSets_Enum

[CODE]
Private Function TxtFile_WriteString(ByVal hTxtFileOut As Long, ByVal xString As String) As Boolean
  Dim xLong1 As Long
  Dim xLong2 As Long
  Dim xLong3 As Long
  Dim xLong4 As Long
  Dim xType1 As TxtFileWriteStruct

  If Not hTxtFileOut = 0& Then
    Call RtlMoveMemory(xType1, ByVal hTxtFileOut, TxtFileWriteStructLen)
    If Not hTxtFileOut = -1& Then
      xLong1 = Len(xString)
      If xType1.Encoding = TxtFile_EncodingEnum.CP_WINUNICODE Then
        ' CP_WINUNICODE
        xLong1 = xLong1 * 2&
        xLong3 = WriteFile(xType1.hFile, ByVal StrPtr(xString), xLong1, xLong2, 0&)
        ElseIf xType1.Encoding = TxtFile_EncodingEnum.CP_UTF8 Then
        xLong2 = WideCharToMultiByte(xType1.Encoding, 0&, ByVal StrPtr(xString), xLong1, ByVal 0&, 0&, ByVal 0&, ByVal 0&)
        If Not xLong2 = 0& Then
          xLong4 = LocalAlloc(0&, xLong2 + 1&)
          If Not xLong4 = 0& Then
            xLong1 = WideCharToMultiByte(xType1.Encoding, 0&, ByVal StrPtr(xString), xLong1, ByVal xLong4, xLong2 + 1&, ByVal 0&, ByVal 0&)
            If xLong1 = xLong2 Then
              xLong3 = WriteFile(xType1.hFile, ByVal xLong4, xLong1, xLong2, 0&)
              Call LocalFree(xLong4)
              GoTo Check
              End If
            Call LocalFree(xLong4)
            End If
          End If
        GoTo Fail
        Else
        xLong3 = WriteFile(xType1.hFile, ByVal xString, xLong1, xLong2, 0&)
        End If
Check:
      If xLong1 = xLong2 And Not xLong3 = 0& Then
        TxtFile_WriteString = True
        Else
Fail:
        Call SetEndOfFile(xType1.hFile)
        Call CloseHandle(xType1.hFile)
        xType1.hFile = -1&
        Call RtlMoveMemory(ByVal hTxtFileOut, xType1, TxtFileWriteStructLen)
        End If
      End If
    End If
  End Function