setcaretpos

本文介绍了SetCaretPos函数的功能及其使用方法。该函数能够移动插入标记到指定坐标,适用于多种Windows版本及Windows CE环境。文章详细解释了函数参数与返回值的意义,并提供了注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-5572165936844014&dt=1193665761703&lmt=1193665780&format=336x280_as&output=html&correlator=1193665761687&url=http%3A%2F%2Fwww.codeguru.cn%2Fpublic%2Fiframe%2Fwinapiiframe.htm&color_bg=FFFFFF&color_text=000000&color_link=000000&color_url=FFFFFF&color_border=FFFFFF&ad_type=text&ga_vid=1285758818.1193665762&ga_sid=1193665762&ga_hid=111695597&flash=9&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=32&u_tz=480&u_his=8&u_java=true" frameborder="0" width="336" scrolling="no" height="280" allowtransparency="allowtransparency">     函数功能:该函数将插入标记移动到指定的坐标上。如果拥有该插人标记的窗口是使用CS_OWNDC类样式创建的,那么指定的坐标依据与该窗口相关的设备环境的映射模式而定。

    函数原型:BOOL SetCaretPos(int X,int Y);

    参数:

    X:指定插入标记新的X坐标。

    Y:指定插入标记新的Y坐标。

    返回值:如果函数执行成功,那么返回值为非零;如果函数执行失败,那么返回值为零。若想获取更多错误信息,请调用GetLastError函数。

    备注:函数SetCaretPos不管插入标记是否隐藏都将移动它。系统为每个队列提供一个插入标记。窗口只能对自己拥有的插入标记进行位置的设置。

    速查:Windows NT:3.1及以上版本;Windows:95及以上版本;Windows CE:1.0及以上版本:头文件:Winuser.h;库文件:user32.lib。

详细分析解释一下chromium源码中的下面的函数: class OmniboxViewViews : public OmniboxView, public views::Textfield, #if BUILDFLAG(IS_CHROMEOS) public ash::input_method::InputMethodManager::CandidateWindowObserver, #endif public views::TextfieldController, public ui::CompositorObserver, public TemplateURLServiceObserver { METADATA_HEADER(OmniboxViewViews, views::Textfield) public: // Max width of the gradient mask used to smooth ElideAnimation edges. static const int kSmoothingGradientMaxWidth = 15; OmniboxViewViews(std::unique_ptr<OmniboxClient> client, bool popup_window_mode, LocationBarView* location_bar_view, const gfx::FontList& font_list); OmniboxViewViews(const OmniboxViewViews&) = delete; OmniboxViewViews& operator=(const OmniboxViewViews&) = delete; ~OmniboxViewViews() override; // Initialize, create the underlying views, etc. void Init(); // Exposes the RenderText for tests. #if defined(UNIT_TEST) gfx::RenderText* GetRenderText() { return views::Textfield::GetRenderText(); } #endif // For use when switching tabs, this saves the current state onto the tab so // that it can be restored during a later call to Update(). void SaveStateToTab(content::WebContents* tab); // Called when the window's active tab changes. void OnTabChanged(const content::WebContents* web_contents); // Called to clear the saved state for |web_contents|. void ResetTabState(content::WebContents* web_contents); // Installs the placeholder text with the name of the current default search // provider. For example, if Google is the default search provider, this shows // "Search Google or type a URL" when the Omnibox is empty and unfocused. void InstallPlaceholderText(); // Indicates if the cursor is at the end of the input. Requires that both // ends of the selection reside there. bool GetSelectionAtEnd() const; // Returns the width in pixels needed to display the current text. The // returned value includes margins. int GetTextWidth() const; // Returns the width in pixels needed to display the current text unelided. int GetUnelidedTextWidth() const; // Returns the omnibox's width in pixels. int GetWidth() const; // OmniboxView: void EmphasizeURLComponents() override; void Update() override; std::u16string GetText() const override; using OmniboxView::SetUserText; void SetUserText(const std::u16string& text, bool update_popup) override; void SetWindowTextAndCaretPos(const std::u16string& text, size_t caret_pos, bool update_popup, bool notify_text_changed) override; void SetAdditionalText(const std::u16string& additional_text) override; void EnterKeywordModeForDefaultSearchProvider() override; bool IsSelectAll() const override; void GetSelectionBounds(std::u16string::size_type* start, std::u16string::size_type* end) const override; void SelectAll(bool reversed) override; void RevertAll() override; void SetFocus(bool is_user_initiated) override; bool IsImeComposing() const override; gfx::NativeView GetRelativeWindowForPopup() const override; bool IsImeShowingPopup() const override; // views::Textfield: gfx::Size GetMinimumSize() const override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnPaint(gfx::Canvas* canvas) override; void ExecuteCommand(int command_id, int event_flags) override; void OnInputMethodChanged() override; void AddedToWidget() override; void RemovedFromWidget() override; std::u16string GetLabelForCommandId(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; // For testing only. OmniboxPopupView* GetPopupViewForTesting() const; protected: // OmniboxView: void UpdateSchemeStyle(const gfx::Range& range) override; // views::Textfield: void OnThemeChanged() override; bool IsDropCursorForInsertion() const override; // Wrappers around Textfield methods that tests can override. virtual void ApplyColor(SkColor color, const gfx::Range& range); virtual void ApplyStyle(gfx::TextStyle style, bool value, const gfx::Range& range); private: friend class TestingOmniboxView; FRIEND_TEST_ALL_PREFIXES(OmniboxPopupViewViewsTest, EmitAccessibilityEvents); // TODO(tommycli): Remove the rest of these friends after porting these // browser tests to unit tests. FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsTest, CloseOmniboxPopupOnTextDrag); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsTest, FriendlyAccessibleLabel); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsTest, DoNotNavigateOnDrop); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsTest, AyncDropCallback); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsTest, AccessibleTextSelectBoundTest); enum class UnelisionGesture { HOME_KEY_PRESSED, MOUSE_RELEASE, OTHER, }; // Update the field with |text| and set the selection. |ranges| should not be // empty; even text with no selections must have at least 1 empty range in // |ranges| to indicate the cursor position. void SetTextAndSelectedRange(const std::u16string& text, const gfx::Range& selection); // Returns the selected text. std::u16string_view GetSelectedText() const; void UpdateAccessibleTextSelection() override; // Paste text from the clipboard into the omnibox. // Textfields implementation of Paste() pastes the contents of the clipboard // as is. We want to strip whitespace and other things (see GetClipboardText() // for details). The function invokes OnBefore/AfterPossibleChange() as // necessary. void OnOmniboxPaste(); // Handle keyword hint tab-to-search and tabbing through dropdown results. bool HandleEarlyTabActions(const ui::KeyEvent& event); void ClearAccessibilityLabel(); void SetAccessibilityLabel(const std::u16string& display_text, const AutocompleteMatch& match, bool notify_text_changed) override; // Returns true if the user text was updated with the full URL (without // steady-state elisions). |gesture| is the user gesture causing unelision. bool UnapplySteadyStateElisions(UnelisionGesture gesture); #if BUILDFLAG(IS_MAC) void AnnounceFriendlySuggestionText(); #endif // Get the preferred text input type, this checks the IME locale on Windows. ui::TextInputType GetPreferredTextInputType() const; // OmniboxView: void SetCaretPos(size_t caret_pos) override; void UpdatePopup() override; void ApplyCaretVisibility() override; void OnTemporaryTextMaybeChanged(const std::u16string& display_text, const AutocompleteMatch& match, bool save_original_selection, bool notify_text_changed) override; void OnInlineAutocompleteTextMaybeChanged( const std::u16string& user_text, const std::u16string& inline_autocompletion) override; void OnInlineAutocompleteTextCleared() override; void OnRevertTemporaryText(const std::u16string& display_text, const AutocompleteMatch& match) override; void OnBeforePossibleChange() override; bool OnAfterPossibleChange(bool allow_keyword_ui_change) override; void OnKeywordPlaceholderTextChange() override; gfx::NativeView GetNativeView() const override; void ShowVirtualKeyboardIfEnabled() override; void HideImeIfNeeded() override; int GetOmniboxTextLength() const override; void SetEmphasis(bool emphasize, const gfx::Range& range) override; // views::View void OnMouseMoved(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; // views::Textfield: bool IsItemForCommandIdDynamic(int command_id) const override; void OnGestureEvent(ui::GestureEvent* event) override; bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; void OnFocus() override; void OnBlur() override; std::u16string GetSelectionClipboardText() const override; void DoInsertChar(char16_t ch) override; bool IsTextEditCommandEnabled(ui::TextEditCommand command) const override; void ExecuteTextEditCommand(ui::TextEditCommand command) override; bool ShouldShowPlaceholderText() const override; void UpdateAccessibleValue() override; // ash::input_method::InputMethodManager::CandidateWindowObserver: #if BUILDFLAG(IS_CHROMEOS) void CandidateWindowOpened( ash::input_method::InputMethodManager* manager) override; void CandidateWindowClosed( ash::input_method::InputMethodManager* manager) override; #endif // views::TextfieldController: void ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) override; bool HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) override; void OnBeforeUserAction(views::Textfield* sender) override; void OnAfterUserAction(views::Textfield* sender) override; void OnAfterCutOrCopy(ui::ClipboardBuffer clipboard_buffer) override; void OnWriteDragData(ui::OSExchangeData* data) override; void OnGetDragOperationsForTextfield(int* drag_operations) override; void AppendDropFormats( int* formats, std::set<ui::ClipboardFormatType>* format_types) override; ui::mojom::DragOperation OnDrop(const ui::DropTargetEvent& event) override; views::View::DropCallback CreateDropCallback( const ui::DropTargetEvent& event) override; void UpdateContextMenu(ui::SimpleMenuModel* menu_contents) override; // ui::SimpleMenuModel::Delegate: bool IsCommandIdChecked(int id) const override; // ui::CompositorObserver: void OnCompositingDidCommit(ui::Compositor* compositor) override; void OnCompositingStarted(ui::Compositor* compositor, base::TimeTicks start_time) override; void OnDidPresentCompositorFrame( uint32_t frame_token, const gfx::PresentationFeedback& feedback) override; void OnCompositingShuttingDown(ui::Compositor* compositor) override; // TemplateURLServiceObserver: void OnTemplateURLServiceChanged() override; // Permits launch of the external protocol handler after user actions in // the omnibox. The handler needs to be informed that omnibox input should // always be considered "user gesture-triggered", lest it always return BLOCK. void PermitExternalProtocolHandler(); // Drops dragged text and updates `output_drag_op` accordingly. void PerformDrop(const ui::DropTargetEvent& event, ui::mojom::DragOperation& output_drag_op, std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner); // Helper method to construct part of the context menu. void MaybeAddSendTabToSelfItem(ui::SimpleMenuModel* menu_contents); // Called when the popup view becomes visible. void OnPopupOpened(); // Helper for updating placeholder color depending on whether its a keyword or // DSE placeholder. void UpdatePlaceholderTextColor(); // When true, the location bar view is read only and also is has a slightly // different presentation (smaller font size). This is used for popups. bool popup_window_mode_; // Owns either an OmniboxPopupViewViews or an OmniboxPopupViewWebUI. std::unique_ptr<OmniboxPopupView> popup_view_; base::CallbackListSubscription popup_view_opened_subscription_; // Selection persisted across temporary text changes, like popup suggestions. gfx::Range saved_temporary_selection_; // Holds the user's selection across focus changes. There is only a saved // selection if this range IsValid(). gfx::Range saved_selection_for_focus_change_; // Tracking state before and after a possible change. State state_before_change_; bool ime_composing_before_change_ = false; // |location_bar_view_| can be NULL in tests. raw_ptr<LocationBarView> location_bar_view_; #if BUILDFLAG(IS_CHROMEOS) // True if the IME candidate window is open. When this is true, we want to // avoid showing the popup. So far, the candidate window is detected only // on Chrome OS. bool ime_candidate_window_open_ = false; #endif // True if any mouse button is currently depressed. bool is_mouse_pressed_ = false; // Applies a minimum threshold to drag events after unelision. Because the // text shifts after unelision, we don't want unintentional mouse drags to // change the selection. bool filter_drag_events_for_unelision_ = false; // Should we select all the text when we see the mouse button get released? // We select in response to a click that focuses the omnibox, but we defer // until release, setting this variable back to false if we saw a drag, to // allow the user to select just a portion of the text. bool select_all_on_mouse_release_ = false; // Indicates if we want to select all text in the omnibox when we get a // GESTURE_TAP. We want to select all only when the textfield is not in focus // and gets a tap. So we use this variable to remember focus state before tap. bool select_all_on_gesture_tap_ = false; // Whether the user should be notified if the clipboard is restricted. bool show_rejection_ui_if_any_ = false; // Keep track of the word that would be selected if URL is unelided between // a single and double click. This is an edge case where the elided URL is // selected. On the double click, unelision is performed in between the first // and second clicks. This results in both the wrong word to be selected and // the wrong selection length. For example, if example.com is shown and you // try to double click on the "x", it unelides to https://example.com after // the first click, resulting in "https" being selected. size_t next_double_click_selection_len_ = 0; size_t next_double_click_selection_offset_ = 0; // The time of the first character insert operation that has not yet been // painted. Used to measure omnibox responsiveness with a histogram. base::TimeTicks insert_char_time_; // The state machine for logging the Omnibox.CharTypedToRepaintLatency // histogram. enum { NOT_ACTIVE, // Not currently tracking a char typed event. CHAR_TYPED, // Character was typed. ON_PAINT_CALLED, // Character was typed and OnPaint() called. COMPOSITING_COMMIT, // Compositing was committed after OnPaint(). COMPOSITING_STARTED, // Compositing was started. } latency_histogram_state_; // The currently selected match, if any, with additional labelling text // such as the document title and the type of search, for example: // "Google https://google.com location from bookmark", or // "cats are liquid search suggestion". std::u16string friendly_suggestion_text_; // The number of added labelling characters before editable text begins. // For example, "Google https://google.com location from history", // this is set to 7 (the length of "Google "). int friendly_suggestion_text_prefix_length_; base::ScopedObservation<ui::Compositor, ui::CompositorObserver> scoped_compositor_observation_{this}; base::ScopedObservation<TemplateURLService, TemplateURLServiceObserver> scoped_template_url_service_observation_{this}; PrefChangeRegistrar pref_change_registrar_; base::WeakPtrFactory<OmniboxViewViews> weak_factory_{this}; };
最新发布
08-02
详细分析解释一下chromium源码中的下面的函数: bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield, const ui::KeyEvent& event) { PermitExternalProtocolHandler(); if (event.type() == ui::EventType::kKeyReleased) { // The omnibox contents may change while the control key is pressed. if (event.key_code() == ui::VKEY_CONTROL) { model()->OnControlKeyChanged(false); } return false; } // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes. // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc. if (event.IsUnicodeKeyCode()) { return false; } // Show a notification if the clipboard is restricted by the rules of the // data leak prevention policy. This state is used by the // IsTextEditCommandEnabled(ui::TextEditCommand::PASTE) cases below. base::AutoReset<bool> show_rejection_ui(&show_rejection_ui_if_any_, true); const bool shift = event.IsShiftDown(); const bool control = event.IsControlDown(); const bool alt = event.IsAltDown() || event.IsAltGrDown(); const bool command = event.IsCommandDown(); switch (event.key_code()) { case ui::VKEY_RETURN: { WindowOpenDisposition disposition = WindowOpenDisposition::CURRENT_TAB; if ((alt && !shift) || (shift && command)) { disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; } else if (alt || command) { disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; } else if (shift) { disposition = WindowOpenDisposition::NEW_WINDOW; } // According to unit tests and comments, holding control when pressing // enter has special behavior handled by `AcceptInput` so in this case // the user is selecting their input (possibly with modification like // appending ".com") and not the row match. This is indicated with an // explicit `kNoMatch` line selection. if (model()->PopupIsOpen() && !control) { model()->OpenSelection(model()->GetPopupSelection(), event.time_stamp(), disposition); } else { model()->OpenSelection( OmniboxPopupSelection(OmniboxPopupSelection::kNoMatch), event.time_stamp(), disposition); } return true; } case ui::VKEY_ESCAPE: return model()->OnEscapeKeyPressed(); case ui::VKEY_CONTROL: model()->OnControlKeyChanged(true); break; case ui::VKEY_DELETE: if (shift && model()->PopupIsOpen()) { model()->TryDeletingPopupLine(model()->GetPopupSelection().line); } break; case ui::VKEY_UP: // Shift-up is handled by the text field class to enable text selection. if (shift) { return false; } if (IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_UP)) { ExecuteTextEditCommand(ui::TextEditCommand::MOVE_UP); return true; } break; case ui::VKEY_DOWN: // Shift-down is handled by the text field class to enable text selection. if (shift) { return false; } if (IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_DOWN)) { ExecuteTextEditCommand(ui::TextEditCommand::MOVE_DOWN); return true; } break; case ui::VKEY_PRIOR: if (control || alt || shift || GetReadOnly()) { return false; } model()->OnUpOrDownPressed(false, true); return true; case ui::VKEY_NEXT: if (control || alt || shift || GetReadOnly()) { return false; } model()->OnUpOrDownPressed(true, true); return true; case ui::VKEY_V: if (control && !alt && IsTextEditCommandEnabled(ui::TextEditCommand::PASTE)) { ExecuteTextEditCommand(ui::TextEditCommand::PASTE); return true; } break; case ui::VKEY_INSERT: if (shift && !control && IsTextEditCommandEnabled(ui::TextEditCommand::PASTE)) { ExecuteTextEditCommand(ui::TextEditCommand::PASTE); return true; } break; case ui::VKEY_BACK: // No extra handling is needed in keyword search mode, if there is a // non-empty selection, or if the cursor is not leading the text. if (model()->is_keyword_hint() || model()->keyword().empty() || HasSelection() || GetCursorPosition() != 0) { return false; } model()->ClearKeyword(); return true; case ui::VKEY_HOME: // The Home key indicates that the user wants to move the cursor to the // beginning of the full URL, so it should always trigger an unelide. if (UnapplySteadyStateElisions(UnelisionGesture::HOME_KEY_PRESSED)) { if (shift) { // After uneliding, we need to move the end of the selection range // to the beginning of the full unelided URL. size_t start, end; GetSelectionBounds(&start, &end); SetSelectedRange(gfx::Range(start, 0)); } else { // After uneliding, move the caret to the beginning of the full // unelided URL. SetCaretPos(0); } TextChanged(); return true; } break; case ui::VKEY_SPACE: { if (model()->PopupIsOpen() && !control && !alt && !shift) { if (model()->OnSpacePressed()) { return true; } OmniboxPopupSelection selection = model()->GetPopupSelection(); if (selection.IsButtonFocused()) { model()->OpenSelection(selection, event.time_stamp()); return true; } } break; } default: break; } if (is_mouse_pressed_ && select_all_on_mouse_release_) { // https://crbug.com/1063161 If the user presses the mouse button down and // begins to type without releasing the mouse button, the subsequent release // will delete any newly typed characters due to the SelectAll happening on // mouse-up. If we detect this state, do the select-all immediately. SelectAll(true); select_all_on_mouse_release_ = false; } return HandleEarlyTabActions(event); }
08-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值